繁体   English   中英

Perl中的正则表达式

[英]Regular Expressions in 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>//; 我怎样才能做到这一点 。?

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;

多种方法。

阅读循环中的下一行:

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替换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM