Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

regex - How can I match against multiple regexes in Perl?

I would like to check whether some string match any of a given set of regexes. How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use smart matching if you have perl version 5.10 or newer!

#! /usr/bin/env perl

use warnings;
use strict;

use feature 'switch';

my @patterns = (
  qr/foo/,
  qr/bar/,
  qr/baz/,
);

for (qw/ blurfl bar quux foo baz /) {
  no warnings 'experimental::smartmatch';
  print "$_: ";
  given ($_) {
    when (@patterns) {
      print "hit!
";
    }
    default {
      print "miss.
";
    }
  }
}

Although you don’t see an explicit ~~ operator, Perl's given/when does it behind the scenes:

Most of the power comes from the implicit smartmatching that can sometimes apply. Most of the time, when(EXPR) is treated as an implicit smartmatch of $_, that is, $_ ~~ EXPR. (See Smartmatch Operator in perlop for more information on smartmatching.)

“Smartmatch Operator” in perlop gives a table of many combinations you can use, and the above code corresponds to the case where $a is Any and $b is Array, which corresponds roughly to

grep $a ~~ $_, @$b

except the search short-circuits, i.e., returns quickly on a match rather than processing all elements. In the implicit loop then, we’re smart matching Any against Regex, which is

$a =~ /$b/

Output:

blurfl: miss.
bar: hit!
quux: miss.
foo: hit!
baz: hit!

Addendum

Since this answer was originally written, Perl’s designers have realized there were mistakes in the way smartmatching works, and so it is now considered an experimental feature. The case used above is not one of the controversial uses, nonetheless the code’s output would include given is experimental and when is experimental except that I added no warnings 'experimental::smartmatch';.

Any use of experimental features involves some risk, but I’d estimate it being low likelihood for this case. When using code similar to the above and upgrading to a newer version of Perl, this is a potential gotcha to be aware of.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...