Reputation: 314
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
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
Upvotes: 4