gpt4 book ai didi

.NET Regex 点字符匹配回车?

转载 作者:行者123 更新时间:2023-12-03 21:27:26 25 4
gpt4 key购买 nike

我用过的每一种正则表达式都带有“.”。字符匹配除新行(\r 或\n)以外的所有内容...当然,除非您启用单行标志。

因此,当我尝试以下 C# 代码时,我感到震惊:

Regex rgx = new Regex(".");
if (rgx.Match("\r\n").Success)
MessageBox.Show("There is something rotten in the state of Redmond!");

它显示了消息。为了确保我不会发疯,我尝试了以下 JavaScript 代码:
if (/./.test("\r\n"))
alert("Something's wrong with JavaScript too.");

JavaScript 没有显示该消息,这意味着它完全按预期工作。

显然,“。” .NET 中的字符与“\r”字符匹配。我查了 documentation看看有没有提到它:

Wildcard: Matches any single character except \n.



哇...从什么时候开始 Regex 风格的点匹配回车?您可能会认为 .NET 的行为与所有其他 Regex 风格一样......尤其是因为它在使用 "\r\n"作为行分隔符的 Windows 环境中。

是否有任何标志/设置可以使其像在其他 Regex 风格中一样工作?是否有任何替代解决方案不涉及替换所有 .带有 [^\r\n] 的字符?

最佳答案

我在编写 Regex Hero 时遇到了同样的问题。这有点奇怪。我写了关于这个问题的博客 here .这导致我向测试器添加了一个功能来启用/禁用 CRLF。无论如何,出于某种原因,Microsoft 选择使用\n(换行符)来标记行尾。

(更新)原因必须与此有关:

Microsoft .NET Framework regular expressions incorporate the most popular features of other regular expression implementations such as those in Perl and awk. Designed to be compatible with Perl 5 regular expressions, .NET Framework regular expressions include features not yet seen in other implementations, such as right-to-left matching and on-the-fly compilation. http://msdn.microsoft.com/en-us/library/hs600312.aspx



正如 Igor 所指出的,Perl 具有相同的行为。

现在,单线和多线 RegexOptions改 rebase 于点和换行的行为。您可以启用 Singleline RegexOption 以便点与换行符匹配。并且您可以启用 Multiline RegexOption 以便 ^ 和 $ 标记每行的开头和结尾(由换行符表示)。但是您无法更改点 (.) 运算符的固有行为以匹配除\r\n 之外的所有内容。

关于.NET Regex 点字符匹配回车?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2282181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com