正則表達式之單行模式與多行模式


單行模式

單行模式(single line mode): 使得 通配符點"." 匹配所有字符,包括換行符(默認情況下,點是不會匹配換行符的)。不過這個模式不被Javascript和Ruby支持。

使用單行模式,只需要在正則表達式的最前面加上 (?s) 就可以了。

下面這個正則表達式可以匹配所有字符(包括換行符):

(?s).*

由於JS不支持這個模式,接下來使用c#來舉一個案例:

static void Main(string[] args)
{
    Regex regex = new Regex("<body>.*</body>");
    String input =
        "<body>\n"+
        "<h1>hello Jame</h1>\n" +
        "<h2>hello Tom</h2>\n" +
        "<h3>hello Volt</h3>\n" +
        "</body>";
    Console.WriteLine("Without single line mode: ");
    Match res = regex.Match(input);
    Console.WriteLine("Whether match success: " + res.Success);
    if (res.Success)
        Console.WriteLine(res.Value);

    Console.WriteLine();
    Console.WriteLine("With single line mode: ");
    regex = new Regex("<body>(?s).*</body>");
    res = regex.Match(input);
    Console.WriteLine("Whether match success: " + res.Success);
    if (res.Success)
        Console.WriteLine(res.Value);
}

輸出為:

Without single line mode:
Whether match success: False

With single line mode:
Whether match success: True
<body>
<h1>hello Jame</h1>
<h2>hello Tom</h2>
<h3>hello Volt</h3>
</body>

 

多行模式

多行模式(multi-line mode):使得^和$匹配到每行字符串的開頭和結尾處,在Ruby中還可以使dot符號匹配所有字符。

使用多行模式,只需要在正則表達式的最前面加上  (?m)  就可以了。

下面這個正則表達式可以對每一行進行匹配:

(?m)^\w+\d+$

案例:

public static void Main()
{
    SortedList<int, string> scores = new SortedList<int, string>();

    string input = "Joe 164\n" +
                    "Sam 208\n" +
                    "Allison 211\n" +
                    "Gwen 171\n";
    string pattern = @"^(\w+)\s(\d+)$";
    bool matched = false;

    Console.WriteLine("Without Multiline option:");
    foreach (Match match in Regex.Matches(input, pattern))
    {
        scores.Add(Int32.Parse(match.Groups[2].Value), (string)match.Groups[1].Value);
        matched = true;
    }
    if (!matched)
        Console.WriteLine("   No matches.");
    Console.WriteLine();

    // Redefine pattern to handle multiple lines.
    // 多行模式可以通過RegexOptions.Multiline參數傳如,或者在正則表達式最前面加上(?m),類似上面得單行模式案例
    pattern = @"^(\w+)\s(\d+)\r*$";
    Console.WriteLine("With multiline option:");
    foreach (Match match in Regex.Matches(input, pattern, RegexOptions.Multiline))
        scores.Add(Int32.Parse(match.Groups[2].Value), (string)match.Groups[1].Value);

    // List scores
    foreach (KeyValuePair<int, string> score in scores)
        Console.WriteLine("{0}: {1}", score.Value, score.Key);
}

輸出為:

Without Multiline option:
   No matches.

With multiline option:
Joe: 164
Gwen: 171
Sam: 208
Allison: 211

 

相關鏈接:

Specifying Modes Inside The Regular Expression

Regular Expression Options


免責聲明!

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



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