-4

I am trying to find a regex that matches brakets that may contain other brakets.

Example:

Match1(Match2())

I want the output to be: Match1:
  $0 => 'Match1(Match2())'
  $1 => 'Match1'
  $2 => 'Match2()'
Match2:   $0 => 'Match2()'
  $1 => 'Match2'
  $2 => ''

Is there a way to get it done, e.g. \w+\(.*?\)

wp78de
  • 18,207
  • 7
  • 43
  • 71
MyD ABD
  • 5
  • 3

1 Answers1

0

The PCRE pattern (([^()]+)\(((?R)?)\)) matches your input as follows:

  • group 1: Match1(Match2())
  • group 2: Match1
  • group 3: Match2()

Note: Python's regex module, Perl, .NET, Ruby 2.0 and PHP support recursive patterns. Other popular languages like JavaScript, Ruby <1.9 and Java don't. See: https://www.regular-expressions.info/recurse.html

Demo: https://regex101.com/r/mX2fG5/57

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • thanks it actully works but what does (?R) do? – MyD ABD May 20 '18 at 09:32
  • 1
    You may change Python 3+ to Python `regex` module. Python 3 uses built-in `re` module that doesn't have any support for these features. Ruby supports on the other hand. – revo May 20 '18 at 09:37
  • @MyDABD checkout the link I added to my answer which explains the details of `(?R)` – Bart Kiers May 20 '18 at 20:36