加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

我如何知道Perl正则表达式的哪一部分与字符串匹配?

发布时间:2020-12-15 21:44:23 所属栏目:大数据 来源:网络整理
导读:我想搜索文件的行以查看它们中的任何一个是否匹配一组正则表达式中的一个. 这样的事情: my @regs = (qr/a/,qr/b/,qr/c/);foreach my $line (ARGV) { foreach my $reg (@regs) { if ($line =~ /$reg/) { printf("matched %sn",$reg); } }} 但这可能很慢. 似
我想搜索文件的行以查看它们中的任何一个是否匹配一组正则表达式中的一个.

这样的事情:

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

但这可能很慢.

似乎正则表达式编译器可以提供帮助.有这样的优化:

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

}

其中’special_function’是特殊的酱,告诉我正则表达式的哪一部分匹配.

解决方法

使用捕获括号.基本思路如下:
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";

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读