首页 > 解决方案 > 使用 Perl 的多个匹配表达式

问题描述

我有一个输入文件,我想从中提取值。输入文件具有这种格式:

 > P-phase pairs total =         5135
 > S-phase pairs total =         4155

我想编写一个与此文本文件中的表达式匹配的 Perl 脚本,并在等号后输出值。下面的代码可以处理第一个值的输出,但我想做的是输出第二个值(4155)。修改此代码以允许多个匹配表达式的最佳方法是什么?谢谢。

#!/usr/bin/perl
use strict;
use warnings;
open (my $file, "<", "input.txt") || die ("cannot open ph2dt file.\n");
open (my $out, ">", "output.txt") || die ("cannot open outfile.\n");

while(my $line =<$file>) {
  chomp $line;
  if ($line =~ / > P-phase pairs total =.*?(\d+)/) {
    print $1;
  }
}

标签: regexperl

解决方案


代替

if ($line =~ / > P-phase pairs total =.*?(\d+)/) {

if ($line =~ / > [PS]-phase pairs total =.*?(\d+)/) {

或者

if ($line =~ / > .-phase pairs total =.*?(\d+)/) {

我们不妨锚定匹配以避免不必要的匹配和回溯,并且.*?应该避免,因为它可能会导致严重的头痛。所以我们得到:

if ($line =~ /^ > .-phase pairs total =\s*(\d+)/) {

推荐阅读