我想检查某个字符串是否与给定的一组正则表达式中的任何一个匹配。我怎样才能做到这一点?
最佳答案
如果您有 perl 5.10 或更高版本,请使用智能匹配!
#! /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!\n";
}
default {
print "miss.\n";
}
}
}
虽然你没有看到明确的
~~
运算符(operator),Perl's given
/ when
在幕后做: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给出了一个你可以使用的多种组合的表格,上面的代码对应的是
$a
的情况是任何和 $b
是数组,大致对应于grep $a ~~ $_, @$b
除了搜索短路,即在匹配时快速返回而不是处理所有元素。然后在隐式循环中,我们将 Any 与 Regex 智能匹配,即
$a =~ /$b/
输出:
模糊:小姐。
酒吧:打!
quux:小姐。
富:打!
巴兹:打!
附录
由于这个答案最初是写的,Perl 的设计者已经意识到智能匹配的工作方式存在错误,所以它是 now considered an experimental feature .上面使用的案例不是有争议的用途之一,尽管如此,代码的输出将包括
given is experimental
和 when is experimental
除了我添加了 no warnings 'experimental::smartmatch';
.任何实验性功能的使用都涉及一些风险,但我估计在这种情况下可能性很小。当使用与上述类似的代码并升级到更新版本的 Perl 时,这是一个需要注意的潜在问题。
关于regex - 如何在 Perl 中匹配多个正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3694322/