你不能用纯正则表达式来做到这一点,但是可以通过一个简单的循环来完成。
JS 示例:
//[.\s\S]* ensures line breaks are matched (dotall not supported in JS)
var exp = /\{\{START\}\}([.\s\S]*)\{\{END\}\}/;
var myString = "{{START}}\ntest\n{{START}}\ntest 2\n{{START}}\ntest 3\n{{START}}\ntest4\n{{END}}\n{{END}}\n{{END}}\n{{END}}";
var matches = [];
var m = exp.exec(myString);
while ( m != null ) {
matches.push(m[0]);
m = exp.exec(m[1]);
}
alert(matches.join("\n\n"));
PHP(我不知道这是否正确,自从我完成 PHP 以来一直如此)
$pattern = "/\{\{START\}\}([.\s\S]*)\{\{END\}\}/";
$myString = "{{START}}\ntest\n{{START}}\ntest 2\n{{START}}\ntest 3\n{{START}}\ntest4\n{{END}}\n{{END}}\n{{END}}\n{{END}}";
$result = preg_match($pattern, $myString, $matches, PREG_OFFSET_CAPTURE);
$outMatches = array();
while ( $result ) {
array_push($outMatches, $matches[0]);
$result = preg_match($pattern, $matches[1], $matches, PREG_OFFSET_CAPTURE);
}
print($outMatches);
输出:
{{START}}
test
{{START}}
test 2
{{START}}
test 3
{{START}}
test4
{{END}}
{{END}}
{{END}}
{{END}}
{{START}}
test 2
{{START}}
test 3
{{START}}
test4
{{END}}
{{END}}
{{END}}
{{START}}
test 3
{{START}}
test4
{{END}}
{{END}}
{{START}}
test4
{{END}}