Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: counting overlapping patterns

by saintmike (Vicar)
on Feb 18, 2005 at 20:19 UTC ( #432495=note: print w/replies, xml ) Need Help??

in reply to counting overlapping patterns

You need to tell the regex engine to pick up after the last match, using the \G anchor:
my $count = 0; my $string = "AAAA"; $count++ while $string =~ /\GAA/gc;
Argh, sorry, I was wrong. Check out this thread instead.

Replies are listed 'Best First'.
Re^2: counting overlapping patterns
by dave_the_m (Monsignor) on Feb 18, 2005 at 20:28 UTC
    $count++ while $string =~ /\GAA/gc;
    Er, no, the \G there serves no purpose as that's the default behaviour anyway. On this other hand this will work, by only consuming the first character of the match:
    $count++ while $string =~ /A(?=A)/g;


      Dave you truly are "the m". That works as promised. Thanks!
Re^2: counting overlapping patterns
by holli (Abbot) on Feb 18, 2005 at 20:25 UTC
    This returns 2. Reasonable because the position of the last match is right after the 2nd "A".
    IŽd like to be disproven, but i think this cannot be solved by a simple regex.
    Disproven ,)

    holli, /regexed monk/
Re^2: counting overlapping patterns
by Anonymous Monk on Feb 18, 2005 at 20:25 UTC
    Ah... the \G anchor, of course.... it doesn't seem to work for me. Still getting 2. Are my cut-n-paste skills poor?

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (1)
As of 2020-10-25 05:34 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (249 votes). Check out past polls.