Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

c# - .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:

enter image description here

But it refuses to work with .net:

enter image description here

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?

question from:https://stackoverflow.com/questions/65917789/regex-c-sharp-optional-suffix-is-ignored-and-returns-wrong-group-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 ( ) 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 ?$ instead of just $.

So, use

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

The .+? ?$ 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:

@"^(#+)[^
]+"

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...