C# System.RegEx matches LF when it should not

前端 未结 2 2206
旧巷少年郎
旧巷少年郎 2020-12-11 06:52

The following returns true

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

so does

Regex.IsMatch(\"FooBar\\n\",          


        
2条回答
  •  被撕碎了的回忆
    2020-12-11 07:22

    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
    

提交回复
热议问题