Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

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.

      Dave you truly are "the m". That works as promised. Thanks!
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?
Re^2: counting overlapping patterns
by holli (Monsignor) 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/

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2019-11-21 13:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (104 votes). Check out past polls.

    Notices?