November 27th, 2006, 03:05 PM
How do I count the number of matches by a regex?
hello, I'm new to perl and regex, I've only been using it for 2 days and I'm having trouble finding an answer to my problem, how do I count how many matches have occured in the string i'm searching? for example:
if I want to find the pattern AAA in it, there will be two matches, how do I get this count if I don't know how many matches there will be in a given string?
November 27th, 2006, 03:33 PM
The /g flag makes the regexp search on $str continue from the last place that it matched. If you don't have the /g at the end, it will restart the search from the beginning each time and you'll have an infinite loop!
$str = "AAABBBAAACCC";
$count = 0;
$count++ while ($str =~ /AAA/g);
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne
"I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
November 27th, 2006, 03:34 PM
I prefer the first method, it's easier to read (i think). The second one surely is shorted and you do counting and replacing in one step. Since this is perl, I'm quite sure there a even more ways to solve this ;-)
my $string = "AAABBBAAACCCDDD";
# method 1:
my $counter1 = 0;
$counter1++ while ($string =~ m/AAA/g);
# method 2:
my $counter2 = ($string =~ s/AAA/AAA/g);
print $counter1, " - ", $counter2,"\n";
November 27th, 2006, 03:38 PM
thanks guys, worked perfectly