Regex 中的多行模式未根据文档执行
Multiline mode in Regex not performing according to documentation
根据 .Net Standard
:
The RegexOptions.Multiline
option, or the m
inline option, enables the
regular expression engine to handle an input string that consists of
multiple lines. It changes the interpretation of the ^
and $
language
elements so that they match the beginning and end of a line, instead
of the beginning and end of the input string.
By default, $
matches only the end of the input string. If you specify
the RegexOptions.Multiline
option, it matches either the newline
character (\n
) or the end of the input string.
(强调我的)
这好像是说$
匹配换行符。然而,情况似乎并非如此。代码:
var m = Regex.Match("123\n456", @"123$", RegexOptions.Multiline);
Console.WriteLine(m.Length);
打印 3
,而不是 4
,如果 $
匹配 newline
。
这是一个错误吗?文档错误?
这是任何锚点的文档错误(^
、$
、\A
、\Z
、\z
、\G
)是 zero-width 个断言,不使用任何文本。 Non-consuming 模式仅匹配字符串中的 位置 ,而不是文本本身。
如果您指定 RegexOptions.Multiline
选项,$
锚点匹配换行符 之前的 位置(\n
,行feed (LF) char) 或输入字符串的末尾。
根据 .Net Standard
:
The
RegexOptions.Multiline
option, or them
inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the^
and$
language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.By default,
$
matches only the end of the input string. If you specify theRegexOptions.Multiline
option, it matches either the newline character (\n
) or the end of the input string.
(强调我的)
这好像是说$
匹配换行符。然而,情况似乎并非如此。代码:
var m = Regex.Match("123\n456", @"123$", RegexOptions.Multiline);
Console.WriteLine(m.Length);
打印 3
,而不是 4
,如果 $
匹配 newline
。
这是一个错误吗?文档错误?
这是任何锚点的文档错误(^
、$
、\A
、\Z
、\z
、\G
)是 zero-width 个断言,不使用任何文本。 Non-consuming 模式仅匹配字符串中的 位置 ,而不是文本本身。
如果您指定 RegexOptions.Multiline
选项,$
锚点匹配换行符 之前的 位置(\n
,行feed (LF) char) 或输入字符串的末尾。