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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.