Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

.net - C# System.RegEx matches LF when it should not

The following returns true

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

so does

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

The RegEx is in SingleLine mode by default, so $ should not match . is not an allowed character.

This is to match a single ASCII PascalCaseWord (yes, it will match a trailing Cap)

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

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (" ") character in the string.

See this documentation:

$   The match must occur at the end of the string or line, or before 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
", @"^[A-Z]([a-z][A-Z]?)+$"));  // => True
Console.WriteLine(Regex.IsMatch("FooBar
", @"^[A-Z]([a-z][A-Z]?)+z")); // => False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...