Regular expression $ in .net framework
I am trying to test $ anchor regex using .net framework, the result is unexpected. $ Anchor only returns the last one. I note that the multi-line switch is important and I've already used it here. Can anyone tell the reason. Below is my test code
Thanks Fred
string sourceText =
@"ab<br />
ab<br />
ab";
//var m = Regex.Match(sourceText, "^a", RegexOptions.Multiline); //this return 3 match
var m = Regex.Match(sourceText, "b$", RegexOptions.Multiline); //this return only one match
while (m.Success)
{
Console.Write(m.Value);
m = m.NextMatch();
}
$
matches only \n
, not \r\n
(as your string is used when using a C # literal in a Windows text file).
The regex b(?=\r?$)
will do what you expect.
See http://msdn.microsoft.com/en-us/library/h5181w5w.aspx for an explanation.
a source to share
There are two reasons why this doesn't work. As Lucero says the $ match will only match the line feed, and your test line has a sharpness answer as well as a line at the end of each line. The second reason is that you are trying to match b at the end of a line and your test line only contains one line that meets this requirement, the first two lines end with a>.
What I suspect you want is something more:
b(?=(?:<br />)?\r?$)
a source to share
There seems to be some doubt as to what exactly you are applying the regex to to. The way it appeared in your original post, the string literal seemed to have literal newlines in it (which weren't even compiled) which replaced the SO software with tags <BR>
. If you want the string to contain newlines, you must use the appropriate escape sequences, for example:
string sourceText = "ab\nab\nab";
or
string sourceText = "ab\r\nab\r\nab";
In any case, the regex b$
must match all three bs when applied in multiline mode. I'm not in the mood to test myself, but if $
really only matches \n
, as the MSDN article says I would consider it as a major flaw in .NET regexes. If the sequence \r\n
, $
must match before \r
and not before \n
.
a source to share