簡體   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