[英]Get all possible matches in regex
例如,我有以下字符串:
(hello(world)) program
我想從字符串中提取以下部分:
(hello(world))
(world)
我一直在嘗試表達式(\\((.*)\\))
但我只得到(hello(world))
。
我如何使用正則表達式來實現
正則表達式可能不是執行此任務的最佳工具。 您可能要使用令牌生成器。 但是,這可以使用正則表達式和遞歸來完成:
$str = "(hello(world)) program";
preg_match_all('/(\(([^()]|(?R))*\))/', $str, $matches);
print_r($matches);
說明:
( # 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.