【问题标题】:Why in perl this regex is not matching line为什么在 perl 中这个正则表达式不匹配行
【发布时间】:2017-02-20 17:38:32
【问题描述】:

我对 perl 代码进行了一些更改,但我无法理解为什么下面的正则表达式与输入行不匹配。

my $regex='^(780200703303)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+([1-9]\\d*)\\s+([1-9]\\d*)\\s+$';
my $line='780200703303    2            0            3            0            0            0            0            0            0            1 ';
if ( $line =~ m/$regex/ ) 
{
    print "Matched";
}

提前致谢

【问题讨论】:

  • 除非您需要多个连续的反斜杠或反斜杠是字符串中的最后一个字符,否则无需在单引号内转义反斜杠。

标签: regex perl


【解决方案1】:

因为0 不匹配[1-9]\d*


您是否考虑过使用以下内容:

my @fields = split ' ', $line;
if ($fields[0] == 780200703303) {
   ...
}

【讨论】:

    【解决方案2】:

    您的测试字符串与正则表达式不匹配。

    my $regex='\\s+([1-9]\\d*)\\s+([1-9]\\d*)\\s+$';
    my $line='            0            1 ';
    

    0 不匹配 ([1-9]\d*)


    使用qr operator 让您的正则表达式更简单。

    my $regex= qr/\s+([1-9]\d*)\s+([1-9]\d*)\s+$/;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      相关资源
      最近更新 更多