使用perl查找字符串中的子字符串

时间:2013-01-29 17:51:06

标签: perl

以下是代码

$string = "any text
Affected area :
menu

Feature to test :

diagnostics
";

$string1=rindex($string,':');
print "$string1\n";

$string2=substr($string,$string1+1);
print "$string2";

我可以使用上面的代码在“要测试的功能”之后找到字符串,但我想找到受影响区域的字符串,例如。 menu.Please help

2 个答案:

答案 0 :(得分:1)

我认为这是某种测试程序。这样做会更有意义吗?

use strict;
use warnings;

my $feature_to_test;
my $affected_area;
while ( my $line <DATA> ) {
    chomp $line;
    if ( $line =~ /^Affected area\s*:/i ) {
        for (;;) {  #Loop forever (until I tell you to stop i.e.)
            my $line = <DATA>;
            if ( $line !~ /^\s*$/ ) {
               $affected_area = $line;
               last;
            }
        }
    }
    if ( $line =~ /^Affected area\s*:/i ) {
        for (;;) {  #Loop forever (until I tell you to stop i.e.)
            my $line = <DATA>;
            if ( $line !~ /^\s*$/ ) {
               $affected_area = $line;
               last;
            }
        }
    }
    if ( $line =~ /^Feature to test\s*:/i ) {
        for (;;) {  #Loop forever (until I tell you to stop i.e.)
            my $line = <DATA>;
            if ( $line !~ /^\s*$/ ) {
               $feature_to_test = $line;
               last;
            }
        }
    }

}
else {
    print qq("Not a special line: "$line"\n);
}

__DATA__
any text
Affected area :
menu

Feature to test :

diagnostics

此方法的优点是它允许您逐行测试,而不是尝试一次解析整个记录。此外,它更好地模拟了文件的读取方式。

也可以使用split将长文本拆分成一个也可以逐行进行的数组:

use strict;
use warnings;

my $string = "any text
Affected area :
menu

Feature to test :

diagnostics
";
my @string_list = split /\n/, $string;  #Now, this is split line by line
for my $line ( @string_list ) {
    print "same logic as above...\n";
}

将此作为循环并读取每一行使逻辑更清晰,更容易理解。它可能效率不高,但即使在经济型PC上,即使在Perl中读取数百万行文件也不会花费超过几秒钟。

答案 1 :(得分:0)

使用positive lookbehind和捕获的正则表达式可能会对此有所帮助:

use strict;
use warnings;

my $string = "any text
Affected area :
menu

Feature to test :

diagnostics
";

my ($area) = $string =~ /(?<=area :\n)(.+)/;

print $area;

输出:

menu