Jeyachandran Rathnam
Jeyachandran Rathnam

Reputation: 314

Get all possible matches in regex

For example I have the following string:

(hello(world)) program

I'd like to extract the following parts from the string:

(hello(world))
(world)

I have been trying the expression (\((.*)\)) but I only get (hello(world)).

How can I achieve this using a regular expression

Upvotes: 0

Views: 344

Answers (1)

Amal Murali
Amal Murali

Reputation: 76656

A regular expression might not be the best tool for this task. You might want to use a tokenizer instead. However this can be done using a regex, using recursion:

$str = "(hello(world)) program";
preg_match_all('/(\(([^()]|(?R))*\))/', $str, $matches);
print_r($matches);

Explanation:

(          # beginning of capture group 1
  \(       # match a literal (
  (        # beginning of capture group 2
    [^()]  # any character that is not ( or )
    |      # OR
    (?R)   # recurse the entire pattern again
  )*       # end of capture group 2 - repeat zero or more times
  \)       # match a literal )
)          # end of group 1

Demo

Upvotes: 4

Related Questions