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
184 views
in Technique[技术] by (71.8m points)

c# - Why doesn't $ in .NET multiline regular expressions match CRLF?

I have noticed the following:

var b1 = Regex.IsMatch("Line1
Line2", "Line1$", RegexOptions.Multiline);   // true
var b2 = Regex.IsMatch("Line1
Line2", "Line1$", RegexOptions.Multiline); // false

I'm confused. The documentation of RegexOptions says:

Multiline: Multiline mode. Changes the meaning of ^ and $ so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.

Since C# and VB.NET are mainly used in the Windows world, I would guess that most files processed by .NET applications use CRLF linebreaks ( ) rather than LF linebreaks ( ). Still, it seems that the .NET regular expression parser does not recognize a CRLF linebreak as an end of line.

I know that I could workaround this, for example, by matching Line1 ?$, but it still strikes me as strange. Is this really the intended behaviour of the .NET regexp parser or did I miss some hidden UseWindowsLinebreaks option?

question from:https://stackoverflow.com/questions/8618557/why-doesnt-in-net-multiline-regular-expressions-match-crlf

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

1 Reply

0 votes
by (71.8m points)

From MSDN:

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

http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx#Multiline

So I can't say why (compatibility with regular expressions from other languages?), but at the very least it's intended.


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

...