#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2002
    Posts
    89
    Rep Power
    13

    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:

    AAABBBAAACCCDDD

    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?


    thanks.
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,616
    Rep Power
    4247
    Code:
    $str = "AAABBBAAACCC";
    $count = 0;
    $count++ while ($str =~ /AAA/g);
    print "$count\n";
    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!
    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
  4. #3
  5. $foo->bar($_);
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2006
    Location
    London
    Posts
    86
    Rep Power
    53
    Code:
    #!/usr/bin/perl
    
    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";
    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 ;-)

    bye,
    grande
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2002
    Posts
    89
    Rep Power
    13
    thanks guys, worked perfectly

IMN logo majestic logo threadwatch logo seochat tools logo