【问题标题】:regex results are different between C# and regex101C# 和 regex101 的正则表达式结果不同
【发布时间】:2018-06-09 10:12:59
【问题描述】:

我创建了以下正则表达式

^xy_yx_blaa_(\d+)([\s\S]*?)(^[A-D]$|QM)+[\s\S]*?(?:SW|Analyzing)

我遇到的问题是,当我运行它时,例如 regex101,它将获得 199 个匹配项(这就是我想要的),但是当我在我的 C# 程序中使用它时,它只会得到 55 个匹配项

经过进一步调查,我发现 C# 程序仅匹配包含“QM”的文本,但在 regex101 中它匹配包含 A|B|C|D|QM 的文本

这是我当前的代码

TextExtractor extractor = new TextExtractor(path);
string text = extractor.ExtractText();
MatchCollection matches = Regex.Matches(text, pattern, RegexOptions.Multiline);

提前致谢

这里是输入字符串的示例

xy_yx_blaa_184

is the act of composing and sending electronic messages, typically
consisting of alphabetic and numeric characters, between two or more
users of mobile phones, tablets, desktops/laptops, or other devices.
Text messages may be sent over a cellular network, or may also be sent
via an Internet connection.

Derived

QM

SW

xy_yx_blaa_199

is the act of composing and sending electronic messages, typically
consisting of alphabetic and numeric characters, between two or more
users of mobile phones, tablets, desktops/laptops, or other devices.
Text messages may be sent over a cellular network, or may also be sent
via an Internet connection.

Derived

A

SW

在上面的文本示例中,C# 将捕获第一个(它包含 QM),但在正则表达式 101 中它将捕获两者

【问题讨论】:

  • 显示输入字符串。
  • 为什么 [A-D] 前面有非 '^' 后面有 $?应该是 ([A-D]|QM)
  • @jdweng: ^ 在这里不是否定,而是行首的锚。
  • @Casimir et Hippolyte 我添加了它
  • @jdweng 完全按照 Casimir 的解释

标签: c# regex text


【解决方案1】:

您应该在使用RegexOptions.Multiline(或其等效的(?m))时在任何$ 之前添加一个可选的\r? 模式,因为文件可能具有Windows CRLF 结尾并且$ 锚点仅在之前匹配\n,LF 符号。

此外,[\s\S] 更像是一个 hack,您需要使用 .RegexOptions.Singleline 来匹配任何字符。

var pattern = @"^xy_yx_blaa_(\d+)(.*?)(^[A-D]\r?$|QM)+.*?(?:SW|Analyzing)";
var results = Regex.Matches(text, pattern, RegexOptions.Multiline | RegexOptions.Singleline)
    .Cast<Match>()
    .Select(m => m.Value)
    .ToList();

这是regex demoC# demo

【讨论】:

    猜你喜欢
    • 2017-12-31
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2019-08-28
    相关资源
    最近更新 更多