Perl中的正则表达式

时间:2014-01-07 10:34:54

标签: regex perl

我正在尝试编写正则表达式以匹配特定行并在其下方的行上执行操作。阅读文件a.txt a.txt

的内容
I am from Melbourne .

Aussie rocks   #The text can be anything below the first line

我正在编写正则表达式来阅读文件a.txt并尝试替换line 1下面的文字。 片段: -

open($fh,"a.txt") or die "cannot open:$!\n";
while(<$fh>){
 if($_=~/^I am from\s+.*/){
   #I have to replace the line below it .
}

任何人都可以帮助我。我只需要replace a line below the line that matches my regex with an empty line or anything$line =~ s/<Line below line1>//;。我怎样才能做到这一点 。?

2 个答案:

答案 0 :(得分:2)

open(my $fh, "<", "a.txt") or die $!;

my $replace;
while(<$fh>){
  $_ = "\n" if $replace;
  $replace = /^I am from.*/;
  print;
}

或立即阅读文件,

open(my $fh, "<", "a.txt") or die $!;
my $str = do { local $/; <$fh> };

$str =~ s/^I am from.*\n \K .*//xm;
print $str;

答案 1 :(得分:1)

方式。

阅读循环中的下一行:

while (<$fh>) {
  print;
  if (/^I am from/) {
    <$fh> // die "Expected line";  # discard next line
    print "Foo Blargh\n";          # output something else
  }
}

这是我首选的解决方案。

使用标志:

my $replace = 0;
while (<$fh>) {
  if ($replace) {
    print "Foo Blargh\n";
    $replace = 0;
  }
  else {
    print;
    $replace = 1 if /^I am from/;
  }
}

整个输入:

my $contents = do { local $/; <$fh> };
$contents =~ s/^I am from.*\ņ\K.*/Foo Blargh/m;
print $contents;

正则表达式需要一个解释:^匹配/m下的一行开头。 .*\n与该行的其余部分匹配。 \K在匹配的子字符串中不包含前面的模式。 .*与下一行匹配,然后由Foo Blargh替换。