Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print message perl number of regex matches

Status
Not open for further replies.
Jun 3, 2007
84
US
Hello all,

I am trying to figure out how to print a message depending on the number of regexes that were matched...either the count or the number that were matched.

Example

if I am running a initial if statement with 5 regex. Depending on the number of matched regex I would like to print a different message. How can I go about doing that. Right now I have the sample code below which prints the actual regex that was matched, so in addition to printing what is shown below I would like to print at the end the number of the regexes that were matched. So for example if one,two,four matches then I would like to print a total of 3 regex matched.

Thanks in advance for the help.

Code:
if ( $string_found =~ /one|two|three|four|five/gim ) {
    if ( $string_found =~ /one/ ) {
        print "One";
    }
    if ( $string_found =~ /two/ ) {
        print "Two";
    }
 
Hi

A hint : capture the matches :
Code:
[u]  DB<1> [/u]$string_found='Two beer, or not two beer.'

[u]  DB<2> [/u]@match=($string_found=~/(one|two|three|four|five)/gim);

[u]  DB<3> [/u]print "found ",scalar @match," matches : ",join ", ",@match;
found 2 matches : Two, two

Feherke.
 
Is this school work?

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
no, trying to add some additional logic to my script. Didn't want to paste/copy my entire script for something this simple.
 
Sample data would be helpful...

Code:
my %counts;#<- declare where/as needed in your script

if ( $string_found =~ /\b(one|two|three|four|five)\b/gio ) {
   $counts{$1}++;
}

# later......
foreach my $key (keys %counts) {
   print "$key = $counts{$key}\n";
}

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top