Search code examples
regexpcre2

Regex using recursion with groups


I am not certain if there's any regex magic that can do this:

foo(f1, f2()) = bar { b1, b2 {}} //match all of this
foo(f3) // dont match this
bar{b3} // dont match this

what I am trying to do is capture an entire line if it contains this pattern:

\w+\((?:[^()]|(?RECURSION ON PARENTHESES))*\)\s*=\s*\w+{(?:[^{}]|(?RECURSION ON CURLY BRACKETS))*}

Solution

  • You can use regex subroutines:

    \w+\s*(\((?:[^()]++|(?-1))*\))\s*=\s*\w+\s*({(?:[^{}]++|(?-1))*})
    

    See the regex demo.

    Details:

    • \w+ - one or more word chars
    • \s* - zero or more whitespaces
    • (\((?:[^()]++|(?-1))*\)) - a substring between paired nested parentheses
    • \s*=\s* - a = char enclosed with zero or more whitespaces
    • \w+\s* - one or more word chars, zero or more whitespaces
    • ({(?:[^{}]++|(?-1))*}) - a substring between paired nested curly braces.

    Note the (?-1) recurses the latest capturing group pattern.