November 27th, 2013, 01:47 PM
What is wrong with my RegEx?
I've just started with C# regex and cannot figure out why I cannot find the firts end of line in the follwoing source
"-- returns Min value of integer parameters \r\n returns Integer\r\n fgdfgdfgdf \r\n dgdfgdg"
My pattern is
new Regex(String.Concat(@"\-\-[A-z\s]+(?=\n)"), RegexOptions.Multiline).Matches(s)
i.e. "Find it started with --, followed by any sequence of words, follwoed by a CR"
And it returns me
"-- returns Min value of integer parameters returns Integer fgdfgdfgdf"
Why not ""-- returns Min value of integer parameters " only?
November 27th, 2013, 03:03 PM
because \s matches newline characters as well, and the + quantifier is greedy, that is, it matches as many characters a possible.
If you only want to match spaces, you have to specify that: [ ]
Matching before a \n character is also problematic, because it may cut off the string after the \r, leaving you with a nonsense character. Instead, use the $ anchor to match the ending of a line. You may have to turn off multiline mode (I'm not sure why you turned in on in the first place).
November 27th, 2013, 03:29 PM