使用Regex和Pushdown-Automata匹配嵌套括号的组 [英] Matching groups of nested parentheses using Regex and Pushdown-Automata

查看:129
本文介绍了使用Regex和Pushdown-Automata匹配嵌套括号的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个可以匹配嵌套结构(在这种情况下为括号)以及任意运算符(在这种情况下为'|'字符)的c#正则表达式.

I'm working on a c# regular expression that can match nested constructions (parentheses in this case) as well as arbitrary operators (a '|' character in this case).

我已开始使用此处.

到目前为止我所拥有的:

What I have so far:

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))"

Note: There may or may not be any operators between the groups. For example, the source may look like "((Name1| Name2) Blah) (Name3 ( Blah | Blah))"

推荐答案

您可以尝试以下操作:(只需在末尾添加|\|)

You can try this: (just adding |\| at the end)

\((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!))\)|\|

这篇关于使用Regex和Pushdown-Automata匹配嵌套括号的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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