C# System.RegEx matches LF when it should not

In .NET regex, the $ anchor (as in PCRE, Python, PCRE, Perl, but not JavaScript) matches the end of line, or the position before the final newline ("\n") character in the string.

See this documentation:

$   The match must occur at the end of the string or line, or before \n at the end of the string or line. For more information, see End of String or Line.

No modifier can redefine this in .NET regex (in PCRE, you can use D PCRE_DOLLAR_ENDONLY modifier).

You must be looking for \z anchor: it matches only at the very end of the string:

\z   The match must occur at the end of the string only. For more information, see End of String Only.

A short test in C#:

Console.WriteLine(Regex.IsMatch("FooBar\n", @"^[A-Z]([a-z][A-Z]?)+$"));  // => True
Console.WriteLine(Regex.IsMatch("FooBar\n", @"^[A-Z]([a-z][A-Z]?)+\z")); // => False

Leave a Comment