【问题标题】:How to find number of matches to regexp in perl6?如何在 perl6 中找到匹配正则表达式的数量?
【发布时间】:2018-09-10 18:47:32
【问题描述】:

在 Perl 5 中我们可以编写

my @things = $text =~ /thing/g;

标量上下文中的$things 是字符串$text 中子字符串thing 的非重叠出现次数。

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

【问题讨论】:

    标签: regex raku


    【解决方案1】:

    我在RosettaCode找到了解决方案。

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

    say '01001011'.comb(/1/).elems;     #prints 4
    

    【讨论】:

    • 请注意,如果正则表达式只包含一个字符串:say '01001011'.comb("1").elems(这大约快 15 倍,因为它不使用正则表达式引擎和很多很多 Match 对象创建)
    • @ElizabethMattijsen 将 RosettaCode 示例更改为使用 Str 作为参数,并注意它与正则表达式基本相同。
    【解决方案2】:

    你可以这样做:

    my $text = 'thingthingthing'
    my @things = $text ~~ m:g/thing/;
    say +@things; # 3
    

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

    【讨论】:

    • Yw。我喜欢清理 cmets,所以我删除了我以前的 cmets。如果您删除您的感谢评论,那么我也会删除此评论。
    猜你喜欢
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 2010-09-10
    • 2015-11-13
    相关资源
    最近更新 更多