问题
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).
I've gotten started by using a push-down automata as described here.
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();
Yields the following results:
// ((Name1| Name2) Blah)
// (Name3 ( Blah | Blah))
Desired results:
// ((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))"
回答1:
You can try this: (just adding |\|
at the end)
\((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!))\)|\|
来源:https://stackoverflow.com/questions/17202321/matching-groups-of-nested-parentheses-using-regex-and-pushdown-automata