2011-12-09 46 views
0

我想提取Perl中兩個單詞之間的單詞,但我不知道我可以使用正則表達式或任何lib來做到這一點?用Perl匹配一個句子中的單詞?

例如:

$sen = "A short quick brown fox jumps over the lazy dog running in the market"; 

@sentence = split//, $sen; 
foreach my $word (@sentence) { 

}   

我想從左側的2個字,並從右側2個字棕色之間獲得的詞放在一起。

output: 

words between: fox jumps over the 
2 words from left: short quick 
2 words from right: dog running 

我怎麼能拿出上面的輸出?

回答

3

這是功課嗎?如果是這樣,那麼你應該在你的問題中這樣說,你得到的答案將旨在幫助你學習,而不是簡單地提供解決方案。

您正在聲明一個包含整個句子字符串的元素的數組,包括開始和結束雙引號。這不可能是你想要的,因爲你的循環只需要將$ word設置爲句子字符串就可以執行一次。

您必須啓動每個Perl程序與

use strict; 
use warnings; 

使調試容易。

下面的代碼完成你描述的內容。

use strict; 
use warnings; 

my $sentence = "A short quick brown fox jumps over the lazy dog running in the market"; 
my @sentence = split ' ', $sentence; 

my @sample = grep /fox/ .. /the/, @sentence; 
print "words between: @sample\n"; 

@sample = @sentence[-2..-1]; 
print "2 words from right: @sample\n"; 

@sample = @sentence[0..1]; 
print "2 words from right: @sample\n"; 

輸出

words between: fox jumps over the 
2 words from right: the market 
2 words from right: A short 
+0

它不是一個分配的一個項目進出口工作,我想匹配「棕色快」左「懶狗」作爲權利不前兩個或最後兩個從您的解決方案中,非常感謝 – aliocee

相關問題