dugar dugar - 1 year ago 77
Perl Question

Regex count adjacent pattern

I'm trying to count adjacent occurrences in a string. For example:

my $pattern = "aa";
my $string = "aaa";

my @matches = $string =~ /($pattern)+/g;
my $c = @matches;

print "$c\n";

This prints 1 but I would like it to be 2 because there are actually 2 adjacent occurrences of "aa" in "aaa"


Answer Source

You can use a zero-width lookahead instead of match:

use strict;
use warnings;

my $pattern = "(?=aa)";
my $string = "aaa";

my @matches = $string =~ /$pattern/g;
my $c = @matches;

print "$c\n"; 
//=> 2

(?=aa) is a positive lookahead that will assert true if it finds aa ahead of current position.

Read more information about Look arounds