• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

C#中换行符\n正则表达式测试

新建一个.NET Core控制台项目,敲入下面代码:

using System;
using System.Text.RegularExpressions;

namespace NetCoreRegularEscapeDemos
{
    class Program
    {
        static void Main(string[] args)
        {
            string text1 = "\n good day!";
            string pattern1 = "^\n.+$";
            string pattern2 = "^\\n.+$";
            string pattern3 = "^\\\n.+$";

            bool isMatched1 = false;
            bool isMatched2 = false;
            bool isMatched3 = false;

            isMatched1 = Regex.IsMatch(text1, pattern1);//true
            isMatched2 = Regex.IsMatch(text1, pattern2);//true
            isMatched3 = Regex.IsMatch(text1, pattern3);//true

            Console.WriteLine("isMatched1={0}", isMatched1);
            Console.WriteLine("isMatched2={0}", isMatched2);
            Console.WriteLine("isMatched3={0}", isMatched3);

            string text2 = "\\n good day!";
            string pattern4 = "^\\\\n.+$";
            bool isMatched4 = false;

            isMatched4 = Regex.IsMatch(text2, pattern4);//true
            Console.WriteLine("isMatched4={0}", isMatched4);

            Console.WriteLine("Press any key to end...");
            Console.ReadKey();
        }
    }
}

运行结果如下所示:

所以可以看到,实际上在C#中,字符串中的换行符"\n",和正则表达式字符串中的"\n"、"\\n"、"\\\n"都是匹配的。

而C#字符串"\\n",用正则表达式字符串"\\\\n",来进行匹配是成功的。

 

posted @ 2020-09-22 18:16  PowerCoder  阅读(2515)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3