Perl正则表达式前瞻性问题



我是Perl的新手,需要知道一个模式来帮助我检查以下内容:

$string="test1n   //   test2   n test3 ";

我想要一个模式来检查test2是否未被注释。我读到了积极和消极的外观广告,并试图实现同样的效果,但它对我不起作用。

以下是代码片段:

$string = "test3n//test2ntest3";
if ($string =~ /(?!//)test2*/) {
  $matched = $&;
  print("$matched");
}
else {
  print("No comments before test2");
}

有人能帮我做上面的图案吗?

根据我的评论,我首先担心的是您的else语句说"test2"没有被评论,但这似乎与您的regex所寻找的相反。

其次,look-ahead将向前查找到字符串中,即在模式之后匹配字符非常有用。要在之前匹配字符,您需要向后看。您可以使用look-behind:来完成此操作

if($string =~ /(?<!//)test2*/)

下面是一个关于Perl前瞻性和前瞻性的教程,它将为您提供更多信息。

test2是否多次出现?

这将检查字符串中是否有test2的注释出现

$str =~ m|//[^Sn]*test2|;

所以

$str !~ m|//[^Sn]*test2|;

将告诉您test2是否有注释事件。

从CPAN加载Regexp::Commonhttps://metacpan.org/module/Regexp::Common并使用其Regexp::Common::comment

#!/usr/bin/env perl
use strict;
use warnings;
# --------------------------------------
use charnames qw( :full :short );
use English qw( -no_match_vars ) ;  # Avoids regex performance penalty
my $string="test1n    //  test2   n test3 ";
use Regexp::Common qw( comment );
if( $string =~ m/ ( $RE{comment}{'C++'} ) /msx ){
  my $comment = $1;
  if( $comment =~ m{ test2 }msx ){
    print $comment;
  }else{
    goto NO_COMMENTS_TEST2;
  }
}else{
  NO_COMMENTS_TEST2:
  print "No comments before test2n";
}

最新更新