5

Lets say my input is fn(a(b,c),d) fn(a,d) fn(a(b),d) and I want a(b,c),d how would I write a pattern to get everything inside of the ()? The 2nd fn() is easy the first and third I don't know how to match

  • Are you given a whitespace character as a separator? You could try `fn[(](\S*)[)]`. – abiessu Aug 19 '13 at 12:23
  • Can `fn` contain more `fn`s, or just `a`/`b`/`c`'s? Does the input contain many `fn`s, or just one? If there are many, are they just `fn`s in a row, or can other thing be between them? How deep is the nesting - is `fn(a(b(c)))` valid? – Kobi Aug 19 '13 at 12:35

2 Answers2

5

You need balancing group definitions for this:

result = Regex.Match(subject,
    @"(?<=\()              # Make sure there's a ( before the start of the match
        (?>                # now match...
           [^()]+          # any characters except parens
        |                  # or
           \(  (?<DEPTH>)  # a (, increasing the depth counter
        |                  # or
           \)  (?<-DEPTH>) # a ), decreasing the depth counter
        )*                 # any number of times
        (?(DEPTH)(?!))     # until the depth counter is zero again
      (?=\))               # Make sure there's a ) after the end of the match",
    RegexOptions.IgnorePatternWhitespace).Value;
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
2

You can split it

var output=Regex.Split(input,@"(?:\)|^)[^()]*(?:\(|$)");

You would get output as

a(b,()c),d
a,d
a(b),d
Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • Your pattern splits anything between `)` and `(`. It will icorrectly split `fn(a(),b())`, and many other variations. (Of course, we don't *know* if these are possible) – Kobi Aug 19 '13 at 12:52
  • @Kobi yes..indeed..u r right..op should confirm this possibility.. – Anirudha Aug 19 '13 at 12:54