我試圖尋找在這樣的多行輸入串中的某個關鍵字,處理多行輸入 - 環路VS正則表達式
this is input line 1
this is the keyword line
this is another input line
this is the last input line
多行輸入存儲在一個變量,名爲「$輸入數據」。現在,我心裏有2種方式來尋找「關鍵字」這個詞,
方法1:
採用分體式放線到一個數組中使用「\ n」分隔符,並使用迭代和過程中的每個線foreach循環,這樣,
my @opLines = split("\n", $inputData);
# process each line individually
foreach my $opLine (@opLines)
{
# look for presence of "keyword" in the line
if(index($opLine, "keyword") > -1)
{
# further processing
}
}
方法2:
使用正則表達式,如下面,
if($inputData =~ /keyword/m)
{
# further processing
}
我想知道這兩種方法是如何相互比較的,以及關於實際代碼性能和執行時間的更好方法是什麼。另外,是否有更好,更有效的方法來完成這項任務?
感謝您的好評!沒有真正用^和$來得到最後一部分,你能澄清嗎?對不起,對於正則表達式有點新... –
除非在正則表達式中使用'^'或'$',否則您不必在regexp之後使用'm'修飾符。它會起作用。 –