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条评论
登录后参与评论

相关文章

来自分类Dev

Perl中的正则表达式

来自分类Dev

Perl中的正则表达式

来自分类Dev

Perl / Curl脚本中的Perl正则表达式

来自分类Dev

Perl中的计算正则表达式替换

来自分类Dev

Perl在正则表达式中的花括号

来自分类Dev

在Perl中编译动态正则表达式

来自分类Dev

正则表达式中的perl意外令牌?

来自分类Dev

在Perl中解释正则表达式

来自分类Dev

Stringr包中的Perl正则表达式

来自分类Dev

Perl正则表达式中的反向引用

来自分类Dev

正则表达式在Perl中不匹配

来自分类Dev

正则表达式中的Perl变量消除歧义

来自分类Dev

Perl脚本中的正则表达式

来自分类Dev

正则表达式替换中的Perl尖括号

来自分类Dev

Perl中替换正则表达式的意外结果

来自分类Dev

Perl与终端中的正则表达式匹配?

来自分类Dev

在Perl中取反正则表达式

来自分类Dev

在Perl中解码正则表达式

来自分类Dev

Perl中的计算正则表达式替换

来自分类Dev

Perl在正则表达式中的花括号

来自分类Dev

Python中的Perl正则表达式

来自分类Dev

Perl正则表达式中的〜m,s和()

来自分类Dev

Perl正则表达式中的反斜杠

来自分类Dev

在Perl中匹配正则表达式的问题

来自分类Dev

正则表达式Perl中的特殊行匹配

来自分类Dev

在Perl中编译动态正则表达式

来自分类Dev

Perl正则表达式中的替换命令?

来自分类Dev

正则表达式中的perl意外令牌?

来自分类Dev

正则表达式在Perl中不匹配