.Net正则表达式将$与字符串的末尾而不是行的末尾匹配,即使启用了多行 [英] .Net regex matching $ with the end of the string and not of line, even with multiline enabled

查看:176
本文介绍了.Net正则表达式将$与字符串的末尾而不是行的末尾匹配,即使启用了多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试突出显示降价代码,但是遇到了.NET regex多行选项的这种奇怪行为.

I'm trying to highlight markdown code, but am running into this weird behavior of the .NET regex multiline option.

以下表达式:^(#+).+$在任何在线正则表达式测试工具上都可以正常工作:

The following expression: ^(#+).+$ works fine on any online regex testing tool:

但是它拒绝使用.net:

But it refuses to work with .net:

它似乎并没有考虑到$标记,只是高亮显示了所有内容,直到字符串结尾,无论如何.这是我的C#

It doesn't seem to take into account the $ tag, and just highlights everything until the end of the string, no matter what. This is my C#

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

我想念什么?

推荐答案

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

It is clear your text contains a linebreak other than LF. In .NET regex, a dot matches any char but LF (a newline char, \n).

请参见 多行模式 MSDN正则表达式参考

See Multiline Mode MSDN regex reference

默认情况下,$仅匹配输入字符串的结尾.如果您指定 RegexOptions.Multiline 选项,它与换行符(\n)或输入字符串的末尾匹配.但是,它与回车/换行符的组合不匹配.要成功匹配它们,请使用子表达式\r?$而不只是$.

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(可选).

The .+?\r?$ will match lazily any one or more chars other than LF up to the first CR (that is optional) right before a newline.

或者只使用否定的字符类:

Or just use a negated character class:

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

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

The [^\r\n]+ will match one or more chars other than CR/LF.

这篇关于.Net正则表达式将$与字符串的末尾而不是行的末尾匹配,即使启用了多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆