研究一下正則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