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",來進行匹配是成功的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM