Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re^2: How to count substrings in an array?

by Athanasius (Chancellor)
on Feb 03, 2013 at 08:20 UTC ( #1016805=note: print w/replies, xml ) Need Help??

in reply to Re: How to count substrings in an array?
in thread How to count substrings in an array?

This works where successive matches do not overlap. But consider the case where the string to match is 'ababa' and the substring is 'aba'. The substring occurs twice in the string, but /$t/g finds only one match, because after the first match the regex engine picks up the search at the point immediately after the last match:

ababa ^ the regex engine starts looking for the second match here

To get overlapping matches, use a positive lookahead:

17:58 >perl -Mstrict -wE "my $s = 'ababa'; my $t = 'aba'; my $c = () = + $s =~ /(?=$t)/g; say $c;" 2 18:02 >

This works, because

  1. a positive lookahead is a zero-width assertion, so the first match does not consume any of the string $s; but
  2. the regex engine advances to (at least) the next character in the string following a successful match.

See Re: Regex: finding all possible substrings by AnomalousMonk.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1016805]
[LanX]: Network (1976 film) yeah
[LanX]: yeah, we just had a discussion at work that SciFi in the 70s had more inovation
[LanX]: (movies)
[Your Mother]: Real ideas. Ideas grounded in reality as well.
[LanX]: still some good newer ones. Oblivion had a great design, Moon was well acted
[Your Mother]: Moon was mind bending and lovely and what's his nose Sam is *always* fun.
[LanX]: the new BS Galactica series is my all time SoapFiction favourite ...
[Your Mother]: I even liked "The Arrival" and I generally hate time travel (oriented) stuff.
[Your Mother]: Gotta go. Stay out of trouble.
[LanX]: no worries ... mainland Europe is safe ;-P

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (11)
As of 2018-03-19 15:08 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (240 votes). Check out past polls.