Regex keep track of `)`

.net, regex

Solution

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;

Problem

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

Original source

Related problems