有没有一种方法可以省略正则表达式中的嵌套括号?
Is there a method to omit nested parentheses in regex?
我正在为 PHP 的 preg_match_all
编写正则表达式函数,以从字符串中查找所有 ifs(...)
及其所有内容。 (在我的示例中,我只有一个如果,因为它不是问题的根源。)
这是我目前得到的:
模式:/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")
问题:正则表达式找到第一个右括号。
我哪里错了?您将如何处理嵌套括号?
实际上你可以做到这一点,这要归功于该页面上 recursive regexps. This is inspired by this comment 的 PHP 功能:
$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")
)
我正在为 PHP 的 preg_match_all
编写正则表达式函数,以从字符串中查找所有 ifs(...)
及其所有内容。 (在我的示例中,我只有一个如果,因为它不是问题的根源。)
这是我目前得到的:
模式:/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")
问题:正则表达式找到第一个右括号。
我哪里错了?您将如何处理嵌套括号?
实际上你可以做到这一点,这要归功于该页面上 recursive regexps. This is inspired by this comment 的 PHP 功能:
$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")
)