C#System.RegEx不应匹配LF [英] C# System.RegEx matches LF when it should not

查看:103
本文介绍了C#System.RegEx不应匹配LF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下返回true

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

也是如此

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

RegEx默认处于SingleLine模式,因此$不应匹配matchn。 \n不允许使用字符。

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

这是为了匹配单个ASCII PascalCaseWord(是的,它将匹配尾随的大写字母)

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

不适用于RegexOptions的任何组合。 RegexOptions.Singleline

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

我在做什么错了?

推荐答案

在.NET正则表达式, $ 锚点(如PCRE,Python,PCRE,Perl,但 not JavaScript)匹配行尾,或字符串中最后一个换行符( \n )字符之前的位置。

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.

请参见此文档


$    匹配项必须在字符串或行的末尾,或在字符串或行的末尾 \n 之前。有关更多信息,请参见结束的字符串或行

$   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.

没有修饰符可以在.NET正则表达式中重新定义(在PCRE中,您可以使用 D PCRE_DOLLAR_ENDONLY 修饰符)。

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

您必须在 \z 锚点:它仅匹配字符串末尾的

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


\z    匹配必须仅在字符串的末尾进行。有关更多信息,请参见结束仅限字符串

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

A 在C#中进行的简短测试:

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

这篇关于C#System.RegEx不应匹配LF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆