Search code examples
regexpcre

How To Recurse Subpattern?


I'm using (\((?>[^()]|(?R))*\)) to match nested parentheses, which matches all of the following cases:

.select( foo(bar()) )
.select( foo() )
.select()

.asdf( foo(bar()) )
.asdf( foo() )
.asdf()

https://regex101.com/r/BSy6Zd/1

However, I only want to match the first three: Only those beginning with/preceded by ".select". My idea was instead of recursing the entire pattern, only recurse the subpattern, so I can match whatever I want prior to the nested parentheses. And of course I can't put a lookbehind after the pattern, since it's not fixed length.

Is there a way to accomplish this?


Solution

  • You can add a capture outside the parens and then use (?1) to indicate recursion on the 1st capture you just created, like this:

    \.select(\((?>[^()]|(?1))*\))
            ^-------------------^
              new capture group
    

    And you get a slight performance increase by using [^()]+:

    \.select(\((?>[^()]+|(?1))*\))
                       ^