简体   繁体   中英

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

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 . 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 . $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 . .*\\n matches the rest of the line. \\K doesn't include the preceding pattern in the matched substring. The .* matches the next line, which is then replaced by Foo Blargh .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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