2014-04-19 43 views
0

我試圖比較列表中的每個單詞到字符串來找到匹配的單詞,但我似乎無法得到這個工作。Perl的正則表達式與預期的不匹配

下面是一些示例代碼

my $sent = "this is a test line"; 


foreach (@keywords) {  # array of words (contains the word 'test') 
    if ($sent =~ /$_/) { 
    print "match found"; 
    } 
} 

看來,如果我手動輸入/test/而不是$_工作,但我不能手動輸入文字。

+0

當我把'@關鍵字=('測試');'在此之前,運行它,我得到'match found'。 –

+0

顯示如何設置'@關鍵字'。 – Barmar

回答

0

你的代碼工作正常。我希望你在真實程序中有use strictuse warnings?這裏有一個例子,我已經填入@keywords,其中包括test

use strict; 
use warnings; 

my $sent = "this is a test line"; 
my @keywords = qw/ a b test d e /; 

foreach (@keywords) { 
    if ($sent =~ /$_/) { 
    print "match found\n"; 
    } 
} 

輸出

match found 
match found 
match found 

所以你的數組不包含你所想象的那樣。我敢打賭,你已經從文件或鍵盤上讀取數據,忘記從chomp的每個單詞末尾刪除換行符。

你可以通過簡單地寫

chomp @keywords 

這將刪除換行符從@keywords所有元素的末尾(如果有的話)。要查看@keywords真正的內容,你可以將這些行添加到您的程序

use Data::Dumper; 
$Data::Dumper::Useqq = 1; 
print Dumper \@keywords; 

您也將看到的元素ae產生匹配以及test,我猜你不想要的。你可以前後的$_值後添加單詞邊界元字符\b,這樣

foreach (@keywords) { 
    if ($sent =~ /\b$_\b/) { 
    print "match found\n"; 
    } 
} 

的正則表達式的定義非常嚴格,只允許字母數字字符或下劃線_,所以Roger's"essay"99%nicely-formatted在這個意義上不是「單詞」。根據您的實際數據,您可能需要不同的東西。

最後,我會更緊湊使用for代替foreach寫這個循環(它們在各方面相同)和if的後綴語句修飾形式,這樣

for (@keywords) { 
    print "match found\n" if $sent =~ /\b$_\b/; 
} 
+0

我懷疑你對換行符是正確的。 – Barmar

+0

@Barmar:是的,我懷疑我也是:) – Borodin