单行模式
单行模式(single line mode): 使得 通配符点"." 匹配所有字符,包括换行符(默认情况下,点是不会匹配换行符的)。不过这个模式不被Javascript和Ruby支持。
使用单行模式,只需要在正则表达式的最前面加上 (?s) 就可以了。
下面这个正则表达式可以匹配所有字符(包括换行符):
(?s).*
由于JS不支持这个模式,接下来使用c#来举一个案例:
static void Main(string[] args)
{
Regex regex= new Regex("
.*");String input=
"
\n"+"
hello Jame
\n" +"
hello Tom
\n" +"
hello Volt
\n" +"";
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("
(?s).*");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
hello Jame
hello Tom
hello Volt
多行模式
多行模式(multi-line mode):使得^和$匹配到每行字符串的开头和结尾处,在Ruby中还可以使dot符号匹配所有字符。
使用多行模式,只需要在正则表达式的最前面加上 (?m) 就可以了。
下面这个正则表达式可以对每一行进行匹配:
(?m)^\w+\d+$
案例:
public static voidMain()
{
SortedList scores = new SortedList();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 inRegex.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 inRegex.Matches(input, pattern, RegexOptions.Multiline))
scores.Add(Int32.Parse(match.Groups[2].Value), (string)match.Groups[1].Value);//List scores
foreach (KeyValuePair score inscores)
Console.WriteLine("{0}: {1}", score.Value, score.Key);
}
输出为:
Without Multiline option:
No matches.
With multiline option:
Joe: 164
Gwen: 171
Sam: 208
Allison: 211
相关链接:
原文:https://www.cnblogs.com/HDK2016/p/13329410.html