RegexOptions.Multiline和RegexOptions.Singleline
RegexOptions.Singleline:指定单行模式。更改点 (.) 的含义,使它与每一个字符匹配(而不是与除 \n 之外的每个字符匹配)。 这是MSDN上面的解释。在正则表达式中"."是与"\n"之外的所有字符匹配的。当使用Singleline的时候,在使用"."的情况下会实现跨行匹配,在使用Multiline的时候不会实现跨行匹配。
View Code
StringBuilder input = new StringBuilder();
input.AppendLine("These is the first test line");
input.AppendLine("These is the second test line");
string pattern2 = @"ne.*";
MatchCollection matchCol = Regex.Matches(input.ToString(), pattern2,RegexOptions.Singleline);
foreach (Match item in matchCol)
{
Console.WriteLine("结果:{0}",item.Value);
}
//在是Singleline的情况下,匹配的结果是ne These is the second test line
//在不是Singleline的情况下,匹配的结果是ne
RegexOptions.Multiline:多行模式。更改 ^ 和 $ 的含义,使它们分别在任意一行的行首和行尾匹配,而不仅仅在整个字符串的开头和结尾匹配(MSDN)。 在正则表达式中,"^"和 "$"表示匹配文本的开头的结束,但是在Multiline的情况下是在任意一行的行首和行尾匹配。
View Code
StringBuilder input = new StringBuilder();
input.AppendLine("These is the first test line");
input.AppendLine("These is the second test line");
string pattern = @"^\w*e";
MatchCollection matchCol = Regex.Matches(input.ToString(), pattern,RegexOptions.Multiline);//获取所有匹配结果,这个匹配结果
foreach (Match item in matchCol)
{
Console.WriteLine("结果:{0}",item.Value);
}
//在multilined的情况下输出是:
结果: These
结果: These
这说明这时"^"不是匹配整个字符串的开头,而是匹配一行字符串的开头。
//在其他情况下输出的是:
结果:These