新建一个.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正则表达式测试

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

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

 

相关文章:

  • 2021-07-03
  • 2022-12-23
  • 2022-12-23
  • 2022-02-13
  • 2022-01-02
  • 2021-07-03
  • 2021-11-10
猜你喜欢
  • 2021-05-14
  • 2022-12-23
  • 2021-11-04
  • 2022-01-12
  • 2021-12-10
相关资源
相似解决方案