如何在perl6中找到regexp的匹配数?

Dan*_*iel 7 regex perl6

在Perl 5中我们可以写

my @things = $text =~ /thing/g;
Run Code Online (Sandbox Code Playgroud)

$things在标量上下文是不重叠的子串出现的次数thing字符串$text.

在Perl 6中如何做到这一点?

Kai*_*epi 7

你可以这样做:

my $text = 'thingthingthing'
my @things = $text ~~ m:g/thing/;
say +@things; # 3
Run Code Online (Sandbox Code Playgroud)

~~匹配左侧与右侧,m:g使测试返回List[Match]包含所有结果.


Dan*_*iel 5

我找到了解决方案RosettaCode.

http://rosettacode.org/wiki/Count_occurrences_of_a_substring#Perl_6

say '01001011'.comb(/1/).elems;     #prints 4
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果正则表达式只包含一个字符串:'say'01001011'.comb("1").elems`(由于它不使用常规字符串大约快15倍),目前你可以更快地使用它.表达式引擎和很多很多`Match`对象创建) (6认同)
  • @ElizabethMattijsen更改了RosettaCode示例以使用Str作为参数,并注意它与正则表达式基本相同. (3认同)