Question

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

Was it helpful?

Solution

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

\((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!))\)|\|
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top