简体   繁体   English

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

[英]Get all possible matches in regex

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)) . 我一直在尝试表达式(\\((.*)\\))但我只得到(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

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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