正则表达式之单行模式与多行模式

单行模式

单行模式(single line mode): 使得 通配符点"." 匹配所有字符,包括换行符(默认情况下,点是不会匹配换行符的)。不过这个模式不被Javascript和Ruby支持。

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

下面这个正则表达式可以匹配所有字符(包括换行符):

(?s).*

由于JS不支持这个模式,接下来使用c#来举一个案例:

static void Main(string[] args)
{
    Regex regex = new Regex("<body>.*</body>");
    String input =
        "<body>
"+
        "<h1>hello Jame</h1>
" +
        "<h2>hello Tom</h2>
" +
        "<h3>hello Volt</h3>
" +
        "</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
" +
                    "Sam 208
" +
                    "Allison 211
" +
                    "Gwen 171
";
    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+)
*$";
    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

原文地址:https://www.cnblogs.com/HDK2016/p/13329410.html