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:
^ 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;"
This works, because
- a positive lookahead is a zero-width assertion, so the first match does not consume any of the string $s; but
- 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,