in reply to Getting the number of times a regexp matches

Here are some more solutions:

$count++ while ($str=~ /$pattern/g); # simple

or

$count= (scalar split /$pattern/, $str ) + ($str=~/$pattern$/) # or it will not be counted - 1; # so it's simpler

Replies are listed 'Best First'.
Re: Re: Getting the number of times a regexp matches
by chipmunk (Parson) on Dec 07, 2000 at 19:07 UTC
    The split solution is not correct, because it does not account for multiple occurences of $pattern at the end of the string:
    $str = 'ababbb'; $pattern = 'b'; $count = (scalar split /$pattern/, $str ) + ($str=~/$pattern$/) - 1; print "$count\n";
    2
    Fortunately, this is an easy problem to fix:
    $count = (scalar split /$pattern/, $str, -1) - 1;
    The third argument to split specifies the maximum number of pieces to split the string into. A negative number turns off the stripping of null fields from the end of the list, without limiting the number of pieces.
Re: Re: Getting the number of times a regexp matches
by t0mas (Priest) on Dec 07, 2000 at 15:41 UTC
    I don't think that the second one will be correct for strings like "blue blue blue and blue again" and patterns like "^blue"...

    Update: Sorry mirod, I misread that one :)

    Lets all have a try at it:
    @_=($str =~ m/$pattern/g) and $count=1+$#_;


    /brother t0mas

      Actually it is, $count gets set to 1