有没有一种方法可以省略正则表达式中的嵌套括号?

时间:2019-02-12 23:01:33

标签: php regex nested parentheses

我正在为PHP的preg_match_all写一个正则表达式函数,以从字符串中查找所有ifs(...)及其所有内容。 (在我的示例中,我只有一个if,因为这并不是问题的根源。)

这是到目前为止我得到的:

模式:/ifs\(.*?\)/i

字符串:=iferror(ifs(OR("foo", "bar"),"a",OR("tar", "scar"),"b",OR("lar"),"d"),"c")

当前输出:ifs(OR("foo", "bar")

预期输出:ifs(OR("foo", "bar"),"a",OR("tar", "scar"),"b",OR("lar"),"d")

问题:正则表达式找到第一个右括号。

我要去哪里错了?以及如何处理嵌套括号?

演示:https://regex101.com/r/SgBqbW/1

1 个答案:

答案 0 :(得分:1)

实际上,由于recursive regexps的PHP功能,您可以执行此操作。灵感来自该页面上的this comment

$string = '=iferror(ifs(OR("foo", "bar"),"a",OR("tar", OR("scar", "baa")),"b",OR("lar"),"d"),"c")
blah blah ifs(OR("foo", "bar"),"a") and another one ifs("a", OR("tar", OR("scar", "baa")),"b",OR("lar"),"d")';
$regex = '/ifs(\(((?>[^()]+)|(?-2))*\))/';
preg_match_all($regex, $string, $matches);
print_r($matches[0]);

输出:

Array (
    [0] => ifs(OR("foo", "bar"),"a",OR("tar", OR("scar", "baa")),"b",OR("lar"),"d")
    [1] => ifs(OR("foo", "bar"),"a")
    [2] => ifs("a", OR("tar", OR("scar", "baa")),"b",OR("lar"),"d") 
)

Demo on 3v4l.org