Search code examples
regexpcre

Balanced-parentheses problem: match function parameters


I need a PCRE regex to match a particular balanced-parentheses situation, and while I've looked at a bunch of discussions of the problem (e.g. here), I can't get anything to work. I'm trying to use regex101.com to debug.

I'm trying to match a string like foo inside MyFunction(foo), where foo can be anything, including other function calls that can themselves contain parentheses. That is, I want to be able to match

MyFunction(23)
MyFunction('Sekret')
MyFunction( 23, 'Sekret', Date() )
MyFunction( Encrypt('Sekret'), Date() )

But MyFunction can be part of a larger string which itself can have parentheses, e.g.

logger.info("MyFunction( Encrypt('Sekret'), Date() )")    

in which case I want only what is passed to MyFunction to be matched, not what is passed to logger.info.

The purpose of this is to replace whatever is passed to MyFunction with something else, e.g. "XXXXXX".

Using a regex from the linked question (e.g. \((?:[^)(]+|(?R))*+\)) will match the outermost set of parens, but if I try to preface it with MyFunction—i.e. if I try the regex MyFunction\((?:[^)(]+|(?R))*+\)—it fails.


Solution

  • regex: MyFunction(\((?>\((?<c>)|[^()]+|\)(?<-c>))*(?(c)(?!))\))

    demo

    updated regex , supports PCRE.

    MyFunction\((?:[^()]*(?:\([^()]*\))*[^()]*)*\)

    demo2

    updated again regex, supports nested function

    MyFunction\(((?:[^()]++|\((?1)\))*)\)

    demo3