我创建了以下正则表达式
^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 中,它将捕获两个
最佳答案
在使用 RegexOptions.Multiline
(或其等效的 (? m)
) 因为文件可能有 Windows CRLF 结尾,并且 $
anchor 仅匹配 \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 demo和一个 C# demo .
关于c# - C# 和 regex101 之间的正则表达式结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50773144/