繁体   English   中英

在正则表达式中获取所有可能的匹配项

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM