How to use Regex to get nested matches including their capturing groups?

Viewed 37

I have a string with a nested pattern func(func(doSomething)) and I have a Regex expression: /func\(([^ ]*)\)/gm. I want to get two separate matches where:

Match 1:

match: func(func(doSomething))
group captured:func(doSomething)

Match 2:
match: func(doSomething)
group captured:doSomething

However, I'm only getting a single match with the entire inner 'func' being a capturing group. Here is the regex link: https://regex101.com/r/dUa4SC/1
Is it possible to achieve this using regex? if so Please help me with it.
Thanks

1 Answers

You can build a recursive function to check the regex over the matched groups, in JavaScript it would be something like this:

function RecursiveMatch(pattern, text){

  let matches = text.match(pattern);

  if(matches != null && matches.length > 1){
    console.log(matches[1] + " found in "+ matches[0])
    RecursiveMatch(pattern, matches[1])
  }    
}

RecursiveMatch("func\\\(([^ ]*)\\\)", "func(func(doSomething))");

And this is the output:

func(doSomething) found in func(func(doSomething))
doSomething found in func(doSomething)
Related