【问题标题】:Searching equal operator in a text file in perl在perl的文本文件中搜索等号运算符
【发布时间】:2014-05-27 04:55:45
【问题描述】:

我有一个文本文件,它在行首多次出现如下所示的等号。我怎样才能提取这样的一行。我已经尝试了下面的代码,但它不起作用。任何关于它为什么不匹配的线索?

文本文件行:

[==========] 10 tests from 4 test cases ran. (43950 ms total)

代码:

if (/^\Q[==========]\E/ .. /^\Qran\)\E/) {
        print "$i.Match Found:".$_."\n";
        $i++;
   }

【问题讨论】:

    标签: perl


    【解决方案1】:

    试试这个,没有测试过,但应该可以。我已经测试了正则表达式并且它可以工作。

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    open (somefile, 'data.txt');
    
    while(<somefile>) {
      chomp;
      if ( $_ =~ m/^\[==========\]/ ) {
        print "Match found: ";
      }
    }
    
    close (somefile);
    

    出于澄清目的; chomp 从行尾删除新行,在这种情况下不是必需的。

    【讨论】:

      【解决方案2】:
      #!/usr/bin/perl
      # your code goes here
      use strict;
      use warnings;
      while(chomp(my $line = <DATA>)) {
        if ( $line =~ m$^\[=.*?]$ ){
          print "Line which starts with [==] is $line\n";
        }
      }
      __DATA__
      [==========] 10 tests from 4 test cases ran. (43950 ms total)
      A line without the equal signs at the beginning
      [==========] 4 tests from 2 test cases ran. (30950 ms total)
      [===]A line with equal signs at beginning.
      

      Demo

      【讨论】:

      • 鉴于问题仅在方括号内显示等于字符,匹配表达式可能会替换为 m$^\[=+\]$。如果可能有其他字符,则可能会使用匹配表达式 m$^\[=[^\]]*\]$ - 尽管所有转义和非转义方括号可能会造成混淆。
      【解决方案3】:

      您正在使用触发器运算符,它将匹配从第一个正则表达式开始到第二个正则表达式(或数据末尾)结束的行。从您使用的正则表达式来看,我认为这不是您的意图。

      要匹配以[==========] 开头的行并提取所有内容直到单词ran,您需要使用capture group

      if (/^\Q[==========]\E(.*?ran)/) {
          print "$. Match Found: $1\n";
      }
      

      括号匹配直到并包括ran 的任何字符,然后将它们放在特殊的$1 变量中。还要注意使用$.,当前行号,以节省您与$i 保持计数。

      如果您只想提取可以使用的数字:

      if (/^\Q[==========]\E (\d+) tests from (\d+) test cases ran/) {
          print "$. Match Found: $1 $2\n";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-11
        • 1970-01-01
        • 1970-01-01
        • 2014-12-28
        • 2011-12-07
        • 1970-01-01
        • 2022-11-13
        相关资源
        最近更新 更多