perl脚本/正则表达式以避免特定模式

时间:2016-12-09 21:58:34

标签: regex perl

我正在尝试在文件中查找模式,并在找到模式时执行操作。模式为class <class_name> extends。但我想排除我遇到模式//class <class_name> extends的情况,即当我得到注释行时我想跳过操作。

open my $fh, "<", $file_t or die "can't read open '$file_t': $OS_ERROR";        # Opening the file
while (<$fh>) {

    if(/class\s{1,10}<class_name>\s{1,10}extends/){
        #Perform the operation if we find above pattern
    }
 close $fh or die "can't read close '$file_t': $OS_ERROR";                      #Closing the file
}

如何包含这段代码以排除我提到的模式。 谢谢你的帮助。

***********编辑************

我想我必须重新构思我的问题。我还想确保当我查找class <class_name> extends时,我应该只查找该模式,而不是在该模式与//之前存在的情况下。有点像,做“if if only only”特定模式而没有其他字符组合。

3 个答案:

答案 0 :(得分:2)

如果您需要在同一个Regex表达式中包含该检查(而不是将两个与and绑在一起,则可以使用否定前瞻:

if (m{/^(?:(?!//).)*class\s{1,10}$className\s{1,10}extends}) {

答案 1 :(得分:2)

一种解决方案是在定义之前只允许空格(如果类可以在缩进的范围内声明)

z = [a, b]
z*z.T (transpose of the z)
=
[[a**2, a*b]
[b*a, b**2]]

解释

/^\s*class\s+<class_name>\s+extends/

答案 2 :(得分:0)

我想我在上述评论的帮助下找到了解决方案。我在我的代码中包含了以下代码行: if(/^\s*\/\/class\s{1,10}<class_name>\s{1,10}extends/){next;}

新代码看起来像这样:

open my $fh, "<", $file_t or die "can't read open '$file_t': $OS_ERROR";        # Opening the file
while (<$fh>) {
if(/^\s*\/\/class\s{1,10}<class_name>\s{1,10}extends/){next;}
elsif(/class\s{1,10}<class_name>\s{1,10}extends/){
    #Perform the operation if we find above pattern
}
close $fh or die "can't read close '$file_t': $OS_ERROR";                      #Closing the file
}

感谢您的帮助。