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>//;我怎样才能做到这一点 。?

阿蒙

多种方法。

阅读循环中的下一行:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章