2011-03-26 83 views
2

我試圖匹配從最後一次出現的關鍵字(foo或bar)到字符串末尾的所有內容。正則表達式匹配從最後一次出現的任何關鍵字的所有內容

例(一):

// I want to match ' foo do you?'; 
$source = 'This is foo and this is bar i like foo do you?'; 
$pattern = '/pattern/'; 
preg_match($pattern, $source, $matches); 

我試過如下:

$pattern = '/((foo|bar) .*)$/'; 

思考它將匹配的foo和所有下面的文字中最後一次出現,但它不是第一次出現匹配。

print_r($matches); 

/* 
Array 
(
    [0] => foo and this is bar i like foo do you? 
    [1] => foo and this is bar i like foo do you? 
    [2] => foo 
) 
*/ 

注意我關心的理論和如何做到這一點的推理,所以請添加一些解釋或鏈接到相關解釋,請。

+0

我在示例中使用了PHP,但語言無關緊要。我唯一的標準是該模式符合PCRE。 – xzyfer 2011-03-26 03:46:47

回答

3
.+((foo|bar).+)$ 

。+匹配前面的許多字符。

((FOO |巴)比賽和捕捉您的關鍵字

+。)比賽和捕獲許多字符。

$匹配字符串/行的結尾。

使用你的例子:

This is foo and this is bar i like foo do you? 
            ^---------^ 
+0

爲了澄清,刪除'?:'然後將我的關鍵字'(foo | bar)'添加到我的匹配中是否正確? – xzyfer 2011-03-26 03:50:01

+0

另外,有沒有一種方法來適應這個解決方案,而不匹配字符串的開始?即'^。+'。實質上告訴正則表達式模式匹配器從字符串的末尾評估我的模式? – xzyfer 2011-03-26 03:55:51

+0

我刪除了?:爲清楚起見,因爲它不是必需的。我也更新了示例,並刪除了「^」,因爲它可能不需要。這將匹配從最後的「foo」或「bar」開始到字符串/行的結尾。 – 2011-03-26 04:05:07

2

使用貪婪匹配前面的模式之前消耗盡可能多的乾草堆,你可以:

>>> import re 
>>> source = 'This is foo and this is bar i like foo do you?' 
>>> pattern = '.*((?:foo|bar).*)' 
>>> re.search(pattern, source).groups()[0] 
'foo do you?' 

做的grottier方式,它是使用負面預測:

>>> # Negative look-ahead for the pattern: (?!.*(?:foo|bar)) 
>>> pattern = '((?:foo|bar)(?!.*(?:foo|bar)).*)' 
>>> re.search(pattern, source).groups()[0] 
'foo do you?' 
相關問題