简体   繁体   中英

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

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:

在此处输入图片说明

But it refuses to work with .net:

在此处输入图片说明

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)

What am I missing?

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 ).

See 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 $ .

So, use

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

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]+"

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

What you have is good. The only thing you're missing is that . doesn't match newline characters, even with the multiline option. You can get around this in two different ways.

The easiest is to use the RegexOptions.Singleline flag which cause newlines to be treated as characters. That way, ^ still matches the start of the string, $ matches the end of the string and . matches everything including newlines.

The other way to fix this (although I wouldn't recomend it for your use case) is to modify your regex to explicitly allow newlines. To do this you can just replace any . with (?:.|\\n) which means either anycharacter or a newline. For your example, you would end up with ^(#+)(?:.|\\n)+$ . If you want to ensure that there's a non-linebreak character first, add an extra dot: ^(#+).(?:.|\\n)+$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM