Is there a Perl shortcut to count the number of matches in a string?

前端 未结 9 872
生来不讨喜
生来不讨喜 2020-12-01 00:54

Suppose I have:

my $string = \"one.two.three.four\";

How should I play with context to get the number of times the pattern found a match (3

相关标签:
9条回答
  • 2020-12-01 01:47

    I think the clearest way to describe this would be to avoid the instant-cast to scalar. First assign to an array, and then use that array in scalar context. That's basically what the = () = idiom will do, but without the (rarely used) idiom:

    my $string = "one.two.three.four";
    my @count = $string =~ /\./g;
    print scalar @count;
    
    0 讨论(0)
  • 2020-12-01 01:57
    my $count = 0;
    my $pos = -1;
    while (($pos = index($string, $match, $pos+1)) > -1) {
      $count++;
    }
    

    checked with Benchmark, it's pretty fast

    0 讨论(0)
  • 2020-12-01 01:57

    Friedo's method is: $a = () = $b =~ $c.

    But it's possible to simplify this even further to just ($a) = $b =~ $c, like so :

    my ($matchcount) = $text =~ s/$findregex/ /gi;
    

    You could thank just wrap this up in a function, getMatchCount(), and not worry about it destroying the passed string.

    On the other hand, you can add in a swap, which may be a bit more computation, but does not result in altering the string.

    my ($matchcount) = $text =~ s/($findregex)/$1/gi;
    
    0 讨论(0)
提交回复
热议问题