Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: counting overlapping patterns

by bobf (Monsignor)
on Feb 19, 2005 at 03:24 UTC ( #432627=note: print w/replies, xml ) Need Help??


in reply to counting overlapping patterns

This might not be as slick as the lookahead approaches described above, but in the spirit of TMTOWTDI here's a version that uses pos and the @- array, which contains the offset of the start of the last match (see perlvar for more info):

sub count_matches { my ( $pattern, $string ) = @_; my $num_matches = 0; while( $string =~ m/$pattern/gi ) { pos( $string ) = $-[0] + 1; $num_matches++ } return $num_matches; }

Update: For monks (like me) that didn't understand why a pattern consisting entirely of a zero-width lookahead assertion (m/(?=AA)/g, see the above responses) doesn't get stuck in an infinite loop, see perlre, "Repeated patterns matching zero-length substring". From that doc:

Perl allows such constructs, by forcefully breaking the infinite loop ... when Perl detects that a repeated expression matched a zero-length substring.

To break the loop, the following match after a zero-length match is prohibited to have a length of zero.

... the second best match is chosen if the best match is of zero length ... the second-best match is the match at the position one notch further in the string.
Thanks to ambrus for the pointer to the right section in the docs.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://432627]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2019-12-08 08:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?