C # System.RegEx matches LF if it shouldn't

The following returns true

Regex.IsMatch("FooBar\n", "^([A-Z]([a-z][A-Z]?)+)$");

      

so that

Regex.IsMatch("FooBar\n", "^[A-Z]([a-z][A-Z]?)+$");

      

RegEx works in SingleLine mode by default, so $ does not have to match \ n. \ N is not a valid character.

This matches one ASCII PascalCaseWord (yes it will match a closable cap)

Doesn't work with any combination of RegexOptions.Multiline | RegexOptions.Singleline

What am I doing wrong?

+3


source to share


2 answers


In .NET regex, the anchor $

(as in PCRE, Python, PCRE, Perl, but not JavaScript) matches the end of the line or the position before the final newline character ( "\n"

) in the string.

See this documentation :

$

  The match must occur at the end of a line or line, or before \n

at the end of a line or line. For more information, see End of Line or Line .

No modifier can override this in a .NET regex (in PCRE you can use a modifier D

PCRE_DOLLAR_ENDONLY

).



You have to look for an anchor \z

: it only matches at the very end of the line:

\z

  The match should only occur at the end of the line. See End of Line Only for more information .

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

      

+1


source


From Wikipedia:

$ Matches the end position of a line, or the position before a line that ends a line. In line tools, it corresponds to the end position of any string.

So you are asking if there is a capital letter of a capital letter followed any number of times (zero or one letter) followed by the end of the line or the position immediately before the new line.



It all seems to be true.

And yes, there seems to be some inconsistency between various sources of documentation as to what counts as a new line and how it works or works exactly. It always reminds of wisdom:

Sometimes a person has a problem and thinks they will use a regular expression to solve it.
Now the man has two problems.

+1


source







All Articles