简体   繁体   English

Perl中的正则表达式

[英]Regular Expressions in Perl

I am trying to write a regex to match a particular line and perform action on the line below it . 我试图编写一个正则表达式来匹配特定的行,并在它下面的行上执行操作。 Reading the file a.txt The contents of a.txt 读文件a.txt的内容a.txt

I am from Melbourne .

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

I am writing a regular expression to read the file a.txt and trying to replace the text below line 1 . 我正在写一个正则表达式来读取文件a.txt并尝试替换第line 1下面的文本。 Snippet :- 片段:-

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

Can anyone please help me. 谁能帮帮我吗。 I just have to replace a line below the line that matches my regex with an empty line or anything . 我只需replace a line below the line that matches my regex with an empty line or anything $line =~ s/<Line below line1>//; . How can I do that .? 我怎样才能做到这一点 。?

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

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

or by reading file at once, 或一次读取文件,

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

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

There are a variety of ways. 多种方法。

Read the next line in the loop: 阅读循环中的下一行:

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

which is my preferred solution. 这是我的首选解决方案。

Use a flag: 使用标志:

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

Slurp the whole input: 包含整个输入:

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

That regex needs an explanation: ^ matches a line start under /m . 该正则表达式需要说明: ^匹配/m下的行开头。 .*\\n matches the rest of the line. .*\\n与该行的其余部分匹配。 \\K doesn't include the preceding pattern in the matched substring. \\K在匹配的子字符串中不包含前面的模式。 The .* matches the next line, which is then replaced by Foo Blargh . .*匹配下一行,然后由Foo Blargh替换。

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

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