regex - 如何在 Perl 中匹配多个正则表达式?

标签 regex perl

我想检查某个字符串是否与给定的一组正则表达式中的任何一个匹配。我怎样才能做到这一点?

最佳答案

如果您有 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 experimentalwhen is experimental除了我添加了 no warnings 'experimental::smartmatch'; .

任何实验性功能的使用都涉及一些风险,但我估计在这种情况下可能性很小。当使用与上述类似的代码并升级到更新版本的 Perl 时,这是一个需要注意的潜在问题。

关于regex - 如何在 Perl 中匹配多个正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3694322/

相关文章:

正则表达式匹配 D 或 E 后跟 2-3 位数字

.net - 正则表达式:前瞻和后视,检查 . (点)用作十进制与句号

javascript - 将数据传递给 CGI 脚本并使用 jQuery.ajax 返回

c++ - 如何使用 Perl 的 C++ 类?

php - Perl 和 PHP 的区别

正则表达式匹配长度小于 150 个字符的字符串

python - 模式内有模式重复的正则表达式

php - RegEx 不适用于长模式 PCRE 的 JIT 编译器堆栈限制 - PHP7

perl - Perl 中@array->[4] 或 %hash->{key} 行为的文档在哪里?

perl 文件::查找和_