【问题标题】:Negating a perl regexp否定 perl 正则表达式
【发布时间】:2011-09-24 05:43:49
【问题描述】:
my ($INV_NB, $USAGE)=split /\|/,"9998|999999999999999";

if ($USAGE=~/^\d{15}\b/)
{
  print "\nUSAGE is Valid\n";
  print "length of $USAGE is ",length($USAGE);  
}

这按预期工作,但我怎样才能否定这个正则表达式?说如果使用不是/^\d{15}\b/

if ($USAGE!=~/^\d{15}\b/)
{
  print "\nUSAGE is Invalid\n";
  print "length of $USAGE is ",length($USAGE);  
}

我试过了,但它不起作用..

【问题讨论】:

  • 还有unless (EXPR) BLOCK可能让意思更明显。

标签: regex perl negate


【解决方案1】:

你可以这样做:

if ($USAGE !~ /^\d{15}\b/)

Perl documentation:

二进制“!~”就像“=〜”除了 返回值在 逻辑意义。

【讨论】:

  • 或者你可以做unless ($USAGE=~/^\d{15}\b/)if (not $USAGE=~/^\d{15}\b/)
【解决方案2】:

还有:

unless ($USAGE=~/^\d{15}\b/)
{
  print "\nUSAGE is Invalid\n";
  print "length of $USAGE is ",length($USAGE);  
}

【讨论】:

    【解决方案3】:

    其他答案是正确的,但如果你想否定一个正则表达式(而不是应用它的运算符),你可以使用

    /^(?!.*?$regex_to_be_negated)/s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多