简体   繁体   中英

Regular expression match count in Perl

I am matching a string of the form A<=>B!C<=>D!E<=>F... and want to do checks on the letters. Basically I want to tell if the letters are in the class according to a hash I have defined. I had the idea of doing the following regex and then looping through the matched strings:

$a =~ /(.)<=>(.)/g;

But I can't figure out to tell how many $1, $2 variables have matched. How do I know how many there are? Also, is there a better way to do this? I am using Perl 5.8.8.

You'll want the 'countof' operator to count the number of matches:

my $count = () = $string =~ /(.)<=>(.)/g;

Replacing the empty list with an array will retain the matches:

my @matches = $string =~ /(.)<=>(.)/g;

Which provides another way to get the $count :

my $count = @matches;   # scalar @matches works too

Use a while loop

use warnings;
use strict;

my %letters = map { $_ => 1 } qw(A C F);
my $s = 'A<=>B!C<=>D!E<=>F';
while ($s =~ /(.)<=>(.)/g) {
    print "$1\n" if exists $letters{$1};
    print "$2\n" if exists $letters{$2};    
}

__END__

A
C
F

创建一个变量并在每次循环时递增它?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM