对于正则表达式应该如何处理嵌套括号的捕获行为,是否有定义的行为?更具体地说,你能合理地预期不同的引擎将捕获第一个位置的外括号,并在后续位置嵌套括号吗?
考虑以下PHP代码(使用PCRE正则表达式)
<?php
$test_string = 'I want to test sub patterns';
preg_match('{(I (want) (to) test) sub (patterns)}', $test_string, $matches);
print_r($matches);
?>
Array
(
[0] => I want to test sub patterns //entire pattern
[1] => I want to test //entire outer parenthesis
[2] => want //first inner
[3] => to //second inner
[4] => patterns //next parentheses set
)
首先捕获整个带括号的表达式(我想测试),然后捕获内括号模式(" want“和" to ")。这是合乎逻辑的,但我可以看到一个同样合乎逻辑的情况是,首先捕获子括号,然后捕获整个模式。
那么,这是在正则表达式引擎中“先捕获整个事物”定义的行为,还是取决于模式的上下文和/或引擎的行为(PCRE不同于C#的不同于Java的不同,等等)?
发布于 2009-08-21 19:57:31
在我工作过的所有平台上,按照左paren的顺序捕获的顺序都是标准的。(perl,php,ruby,egrep)
https://stackoverflow.com/questions/1313934
复制相似问题