.NET(C#):Regex的RegexOptions和行數

來源:互聯網
上載者:User

研究一下正則RegexOptions枚舉的三個針對匹配行的區別,對應None,SingleLine(單行)和Multiline(多行)枚舉值。

 

結論是:

  • None:(.)匹配任何字元除了\n。^和$不起作用。
  • Singleline:(.)匹配任何字元。^和$匹配整個字串
  • Multiline:(.)匹配任何字元除了\n。^和$匹配每行的開頭和結尾。

 

另外貌似目前.NET的正則對\A和\Z支援的不是很好。

下面測試代碼:(注意由於輸出字元中有分行符號,因此用ASCII碼作輸出)

//+ using System.Text.RegularExpressions;

 

static void Main()

{

    var opts = new RegexOptions[]

    {

        RegexOptions.None, RegexOptions.Singleline, RegexOptions.Multiline

    };

 

    //一次用RegexOptions和指定正則來匹配並輸出結果

    foreach (var opt in opts)

    {

        test(opt, @".");

        test(opt, @"^.*$");

    }

}

 

//用指定RegexOptions正則選項和正則來匹配"A\nB"並輸出結果

static void test(RegexOptions opt, string pattern)

{

    Console.WriteLine("=== {0} - \"{1}\"", opt, pattern);

    var regex = new Regex(pattern, opt);

    var match = regex.Match("A\nB");

    while (match.Success)

    {

        PrintString(match.Value);

        match = match.NextMatch();

    }

}

 

//輸出字串的ASCII碼

static void PrintString(string s)

{

    Console.WriteLine(BitConverter.ToString(Encoding.ASCII.GetBytes(s)));

}

 

輸出:

=== None - "."

41

42

=== None - "^.*$"

=== Singleline - "."

41

0A

42

=== Singleline - "^.*$"

41-0A-42

=== Multiline - "."

41

42

=== Multiline - "^.*$"

41

42

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.