.Net 正则表达式匹配 $ 与字符串的结尾而不是行,即使启用了多行

.Net regex matching $ with the end of the string and not of line, even with multiline enabled

我正在尝试突出显示降价代码,但 运行 陷入 .NET 正则表达式多行选项的这种奇怪行为中。

以下表达式:^(#+).+$ 适用于任何在线正则表达式测试工具:

但它拒绝与 .net 一起工作:

它似乎没有考虑 $ 标签,只是突出显示字符串末尾的所有内容,无论如何。这是我的 C#

RegExpression = new Regex(@"^(#+).+$", RegexOptions.Multiline)

我错过了什么?

你有的就是好的。您唯一缺少的是 . 不匹配换行符,即使使用多行选项也是如此。您可以通过两种不同的方式解决这个问题。

最简单的方法是使用 RegexOptions.Singleline 标志,它会将换行符视为字符。这样,^ 仍然匹配字符串的开头,$ 匹配字符串的结尾,. 匹配所有 包括 换行。

解决此问题的另一种方法(尽管我不会为您的用例推荐它)是修改您的正则表达式以明确允许换行符。为此,您可以将任何 . 替换为 (?:.|\n),这意味着任何字符或换行符。对于您的示例,您最终会得到 ^(#+)(?:.|\n)+$。如果你想确保首先有一个非换行符,请添加一个额外的点:^(#+).(?:.|\n)+$

很明显您的文本包含换行符而不是 LF。在 .NET 正则表达式中,点匹配除 LF(换行符,\n)以外的任何字符。

Multiline Mode MSDN regex reference

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. It does not, however, match the carriage return/line feed character combination. To successfully match them, use the subexpression \r?$ instead of just $.

所以,使用

@"^(#+).+?\r?$"

.+?\r?$ 将延迟匹配除 LF 之外的任何一个或多个字符,直到换行符之前的第一个 CR(可选)。

或者直接使用否定字符class:

@"^(#+)[^\r\n]+"

[^\r\n]+ 将匹配 CR/LF 以外的一个或多个字符。