How do I know how much of a Perl regular expression matches a string?

I want to find strings in a file to see if any of them matches one of the set of regular expressions.

something like that:

my @regs = (qr/a/, qr/b/, qr/c/);
foreach my $line (<ARGV>) {
   foreach my $reg (@regs) {
      if ($line =~ /$reg/) {
         printf("matched %s\n", $reg);
      }
   }
}

but it can be slow.

It looks like the regex compiler can help. Is there such an optimization:

my $master_reg = join("|", @regs); # this is wrong syntax. what the right way?
foreach my $line (<ARGV>) {
   $line =~ /$master_reg/;
   my $matched = special_function();
   printf("matched the %sth reg: %s\n", $matched, $regs[$matched]
}

}

where special_function is a special sauce telling me which part of the regular expression was matched.

+5
source share
2 answers

Use brackets to capture. The basic idea is as follows:

my @matches = $foo =~ /(one)|(two)|(three)/;
defined $matches[0]
    and print "Matched 'one'\n";
defined $matches[1]
    and print "Matched 'two'\n";
defined $matches[2]
    and print "Matched 'three'\n";
+8
source

Add capture groups:

"pear" =~ /(a)|(b)|(c)/;
if (defined $1) {
    print "Matched a\n";
} elsif (defined $2) {
    print "Matched b\n";
} elsif (defined $3) {
    print "Matched c\n";
} else {
    print "No match\n";
}

, /(a|b|c)/ $1, "a", "b" "c" , .

, , , , @- @+, . $-[0] , , $-[$n] , n th.

+5

All Articles