Fer*_*ata 9 regex perl6 ratchet
在Perl 6中,可以将波浪号运算符用于嵌套结构。棘轮运动显然会影响嵌套结构的工作方式。
这种情况不使用棘轮:
$ perl6 -e "say '{hello} aaa }' ~~ / '{' ~ '}' ( .+? ) /"
?{hello}?
0 => ?hello?
Run Code Online (Sandbox Code Playgroud)
虽然这样做:
$ perl6 -e"say '{hello} aaa }' ~~ / :r '{' ~ '}' ( .+? ) /"
Nil
Run Code Online (Sandbox Code Playgroud)
通过将.+?模式更改为更具体的内容,可以得到预期的结果<-[}]> +:
$ perl6 -e"say '{hello} aaa }' ~~ / :r '{' ~ '}' ( <-[}]> + ) /"
?{hello}?
0 => ?hello?
Run Code Online (Sandbox Code Playgroud)
但我不知道为什么“节俭量词”不能使用棘轮功能工作。任何的想法?
(使用rakudo 2019.03.1)
在:ratchet正则表达式副词禁止发动机回溯到量化的子模式。
第一个/ :r '{' ~ '}' ( .+? ) /模式表示.+?在匹配任何一个或多个字符(尽可能少)后,该模式将不会被重新测试,并在随后的模式失败时重新输入。
在这里,在您的{hello} aaa }示例中,经过测试{,.+?匹配h,然后}不匹配e。由于不允许回溯,因此匹配失败并且下一次迭代开始:h已测试{,失败了,等等。
The second regex with <-[}]> + works because this matches any 1+ chars other than }, and that is the crucial difference from .+? that could match } and obligatorily consumed at least 1 char (due to +). Thus, it can't consume } and finds a match.