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

Re: counting overlapping patterns

by Eimi Metamorphoumai (Deacon)
on Feb 18, 2005 at 20:39 UTC ( #432509=note: print w/replies, xml ) Need Help??

in reply to counting overlapping patterns

The key is to match without consuming text. The following works.
while("AAAA" =~ /(?=AA)/g){ $count++; }
It'll go through it repeatedly, starting at each position, but never consuming anything.

Replies are listed 'Best First'.
Re^2: counting overlapping patterns
by ikegami (Pope) on Feb 18, 2005 at 21:46 UTC


    while ('AAAA' =~ /A(?=A)/g) { $count++; }

    which looks slightly less weird to me.

      But requires rewriting the pattern. Mine will work even if the pattern comes from a variable, or contains different possibilities for the first character ('/AA|BB/' becomes '/(?=AA|BB)/'). My approach was to try to do minimal tinkering with the original, but yeah, it's not as obvious what's actually going on.
        Good point.

Log In?

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

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

    Results (249 votes). Check out past polls.