2013-06-20 26 views
2

我有一個從Perl中的一個字符串中獲取前一個單詞的場景。例如在一個模式中獲取前一個單詞

$str = "there are lot of apples <xref id=1> and " . 
     "a lot of oranges <xref id=2> as blah blah"; 

我需要之前每個<xref(.*?)>

+0

反向你的思維:可以,就像馬薩建議,正常使用正則表達式。匹配後跟一個字現在向我們展示你試過的東西,以及你被卡住的地方 – amon

回答

2
my $str = "there are lot of apples <xref id=1> and lot of oranges <xref id=2> as blah blah"; 

for my $substr ($str =~ m{(\w+)(?= <xref id)}g) { 
    print "- $substr\n"; 
} 

抓取前一個單詞(「蘋果」和上面的「桔子」)的關鍵是(?=...)一部分。

但是 - 你實際上不需要斷言。從一些很奇怪的邊緣情況

for my $substr ($str =~ m{(\w+)\s+<xhref id}g) { 

,它會工作得細(當然,除了

+1

不需要預測;'m {(\ w +) Massa

+0

Massa:你是對的。 。 – 2013-06-20 15:41:04

相關問題