我正在研究可以匹配嵌套结构(在本例中为括号)以及任意运算符(在本例中为“|”字符)的 C# 正则表达式。
我已经开始使用下推式自动机,如 here 所述.
我目前拥有的:
String pattern = @"
(?# line 01) \(
(?# line 02) (?>
(?# line 03) \( (?<DEPTH>)
(?# line 04) |
(?# line 05) \) (?<-DEPTH>)
(?# line 06) |
(?# line 07) .?
(?# line 08) )*
(?# line 09) (?(DEPTH)(?!))
(?# line 10) \)
";
var source = "((Name1| Name2) Blah) | (Name3 ( Blah | Blah))";
var matches = Regex.Matches(source, pattern,
RegexOptions.IgnorePatternWhitespace);
matches.Dump();
产生以下结果:
// ((Name1| Name2) Blah)
// (Name3 ( Blah | Blah))
期望的结果:
// ((Name1| Name2) Blah)
// |
// (Name3 ( Blah | Blah))
注意:组之间可能有也可能没有任何运算符。例如,来源可能看起来像“((Name1| Name2) Blah) (Name3 ( Blah | Blah))”
最佳答案
你可以试试这个:(只需在末尾添加 |\|
)
\((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!))\)|\|
关于c# - 使用正则表达式和下推自动机匹配嵌套括号组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17202321/