Perl 6:使用捕获进行前瞻

Perl 6: Lookahead with capture

我正在尝试为 this code-golf challenge 编写一个 Perl 6 正则表达式,它使用以下规则拆分字符串:

例如:

66667888    -> '66', '66, '7', '888'
19999999179 -> '1', '99', '99', '999', '1', '7', '9'

我认为正则表达式 m:g/(.)[[=11=][=11=]<![=11=]>|[=11=]?]/ 可以工作,但在负前瞻中使用捕获似乎会破坏它,我不知道如何正确使用它。

根据我的使用方式,它可能 loops forever, throws the error Cannot resolve caller INTERPOLATE_ASSERTION, or returns the wrong result。是否有在先行中使用捕获的正确方法,或者这是一个错误?

根据 Capturing 部分,您需要使用代码块使这些反向引用在正则表达式中可见:

These capture variables are only available outside the regex... In order to make them available inside the regex, you need to insert a code block behind the match; this code block may be empty if there's nothing meaningful to do

使用

given "19999999179" {
  for m:g/(.) {} :my $c = [=10=]; ([ $c$c<!$c> | $c? ])/  -> $match {
    say ~$match;
  }
}

结果:

1
99
99
999
1
7
9

参见Perl6 demo

在这种情况下,您可以将模式收缩为 m:g/(.) {} [ [=13=][=13=]<![=13=]> | [=13=]? ]/:

my @matches;
given "19999999179" {
  for m:g/(.) {} [ [=12=][=12=]<![=12=]> | [=12=]? ]/ -> $match {
    @matches.push: (~$match);
  }
}
say @matches;

结果 [1 99 99 999 1 7 9]

this Perl6 demo