簡體   English   中英

PERL:如何優雅地搜索/替換回車?

[英]PERL: how to search/replace elegantly beyond carriage return?

我在谷歌搜索時遇到了麻煩,因為大多數人似乎都想知道如何刪除回車。

我的代碼有效,但看起來很尷尬,而且我錯過了一些東西。 可能是我的原始腳本設計得很差(我正在檢查一個元素是否最后出現,如果是,我需要更改它),但仍然......似乎我錯過了一個讓事情變得更順暢的快速方法。

use strict;
use warnings;

my $a = "This is a string that I concatenate beforehand with carriage returns, so it's hard to separate out.\nThis is the last line I want to track.\nI want to delete this line.";
my $b = $a;

$b =~ s/(track\.).*/$1/g;

print "THIRD LINE STILL THERE\n$b\n\n";

my @c = split(/\n/, $a);
for (0..$#c) { 
   if ($c[$_] =~ /last line/) { 
      $b = join("\n", @c[0..$_]); 
      last; 
   } 
}

print "THIRD LINE GONE. IT WORKS, BUT I THINK THERE MUST BE A BETTER WAY.\n$b\n";

你的代碼中有一個很好的方法,需要更多一點 - 沒有必要迭代。

這將從多行字符串中刪除最后一行。

my @lines = split '\n', $line;
pop @lines;
my $text = join '\n', @lines;

pop從數組中刪除最后一個元素。 或者,如果你想保持@lines整體

my @lines = split '\n', $line;
my $text = join '\n', @lines[0..$#lines-1];

請注意,如果文本的“最后”行本身以換行符結束(因此,如果后面跟一個空行),則很好地split不會返回額外的元素,因為它會丟棄列表中的所有尾隨空字段然后回來。 所以上面的代碼保持不變。


請注意Jonathan LefflerAlan Moore的評論。 從后者

“換行符”是用於分隔行的任何內容的通用術語,包括換行符( \\n ),回車符( \\r ),回車換行符對( \\r\\n )以及其他一些更奇特的字符。

如果您要查找“ 回車 ”,每個標題或其他形式的“換行符”,您需要調整split\\njoin上方。 例如,請參閱Representations on Wikipedia的“ Representations on Wikipedia

這應該工作:

$b =~ s/track\..*/track\./sg;

您可以使用rindex()獲取字符串中位置的最后一個索引,並將其與substr()組合。 像這樣:

$b = substr($a, 0, rindex($a, "\\n"));

如果要將新行字符保留在字符串的末尾,請執行以下操作:

$b = substr($a, 0, rindex($a, "\\n") + 1);
my $string = $a;
$string =~ s/I want to delete[^\n]*\n//gs;

拆分數組並迭代它並沒有錯。 如果你想在一個正則表達式中執行它,你也可以通過查找目標字符串來完成它。

另外一個注意事項是避免使用$a$b因為它們經常被用作內部變量。

如果我理解你的問題,你似乎需要的是pop

use strict;
use warnings;

my $a = "This is a string that I concatenate beforehand with carriage returns, so it's hard to separate out.\nThis is the last line I want to track.\nI want to delete this line.";

my @lines     = split(/\n/, $a);
my $last_line = pop @lines;

print join('\n', @lines) . "\n"; # first two lines
print $last_line . "\n"; # in case you still want to use it ;)

希望這有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM