所有可能的匹配,比如我有以下字符串:获取正则表达式
(hello(world)) program
我想从一个字符串中提取以下几个部分:
(hello(world))
(world)
我一直在努力表达(\((.*)\))
但我只得到(hello(world))
。
我怎样才能做到这一点使用正则表达式
所有可能的匹配,比如我有以下字符串:获取正则表达式
(hello(world)) program
我想从一个字符串中提取以下几个部分:
(hello(world))
(world)
我一直在努力表达(\((.*)\))
但我只得到(hello(world))
。
我怎样才能做到这一点使用正则表达式
正则表达式可能不适合这个任务的最佳工具。您可能想要使用标记器。然而,这可以使用正则表达式,使用recursion来完成:
$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
Upvote for recursion,bit iffy on the answer,because we still still not WTF the OP want –
上面的代码返回**副本** ..您可以使用'$ new_arr = array_unique(call_user_func_array('array_merge',$ matches ));'摆脱重复。 @AmalMurali –
@ShankarDamodaran:我想知道为什么这甚至是必要的? OP在哪里说他希望重复删除? –
我建议不要使用正则表达式这一点。对于不规则语言来说,这并不有用,尤其是涉及到嵌套时。 –
我会建议你忽略上述(@VasiliSyrakis),因为我们不知道“这是一个像方言一样的LISP!”。递归(PERL REGEX FTW(不是perl本身!))会允许这样做,他可能也想要最内部的匹配,所以'?:'可能是有用的。或者是一场不贪婪的比赛,没有足够的信息来制定他想要的。 –
@VasiliSyrakis Hmm.me是一个新手,你能给出一个简单的解释,为什么正则表达式不是最好的选择? –