如何在后向断言中使用捕获组?
我尝试使用与 answer 中相同的公式.但这似乎不适用于lookbehinds。
从概念上讲,这就是我想要做的。
say "133" ~~ m/ <?after $0+> (\d) $ /
我知道这可以在没有后视的情况下轻松实现,但暂时忽略它:)为此,我尝试了以下选项:
使用
:var
句法:say "133" ~~ m/ <?after $look-behind+> (\d):my $look-behind; $ /;
# Variable '$look-behind' is not declared
使用code block
定义外部变量的语法:my $look-behind;
say "133" ~~ m/ <?after $look-behind+> (\d) {$look-behind=$0} $ /;
# False
似乎问题在于 lookbehind
在“代码块/:my $var”之前执行,因此对于后向树来说,变量是空的。有没有办法在lookbehinds中使用捕获组?
最佳答案
当您在实际捕获之前引用捕获的值时,它不会被初始化,因此您无法获得匹配。您需要在实际使用对捕获值的反向引用之前定义捕获组。
接下来,您需要定义一个代码块并将反向引用分配给要在整个正则表达式模式中使用的变量,否则,它对后向模式不可见。见 this Capturing Raku reference :
This code block publishes the capture inside the regex, so that it can be assigned to other variables or used for subsequent matches
你可以使用类似的东西
say "133" ~~ m/ (\d) {} :my $c=$0; <?after $c ** 2> $ /;
在这里,(\d)
匹配并捕获一个数字,然后使用代码块将此捕获的值分配给 $c
变量,然后是 <?after $c ** 2>
后视检查 $c
value 在当前位置的左侧至少出现两次,然后是 $
anchor 检查当前位置是否是字符串的结尾。见 this online Raku demo .
关于regex - 乐正则表达式 : How to use capturing group inside lookbehinds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65437610/