當我運行在Python 2.7以下聲明,爲什麼python正則表達式替換(A | B)不匹配按照文檔?
re.search('eagle|cat', 'The cat is an animal. The eagle is bird').group()
我期待看到'eagle'
的結果按正則表達式的文檔 但我發現了'cat'
。我在這裏錯過了什麼嗎?
當我運行在Python 2.7以下聲明,爲什麼python正則表達式替換(A | B)不匹配按照文檔?
re.search('eagle|cat', 'The cat is an animal. The eagle is bird').group()
我期待看到'eagle'
的結果按正則表達式的文檔 但我發現了'cat'
。我在這裏錯過了什麼嗎?
的正則表達式與替代的圖案(由|
分隔)不掃描第一替換整個字符串,那麼第二個。
相反,每個替代被認爲是在輸入字符串每個位置。因此,在位置0,既不eagle
也不cat
比賽,但在第4位,cat
比賽,即使eagle
是第一次嘗試。
因此,cat
被返回作爲匹配;其餘的字符串不再需要考慮。
當均爲模式在相同位置將匹配時,備選排序很重要。所以cat|cats
將返回cat
,始終,即使在輸入字符串字後s
:
>>> import re
>>> re.search('cat|cats', 'Like herding cats.').group()
'cat'
>>> re.search('cats|cat', 'Like herding cats.').group()
'cats'
謝謝!那很完美! – elephant
我猜@martijn回答得非常好你的問題,不過,我想指出,你可以使用negative lookahead確保cat
從不其次eagle
,但是,如果cat
來eagle
後,將被匹配:
re.search('eagle|(?!.*eagle)cat', 'The cat is an animal. The eagle is bird.').group()
匹配eagle
如果cat
來後eagle
re.search('eagle|(?!.*eagle)cat', 'The cat is an animal. The eagle is bird, cat is a feline.').group()
將匹配eagle
和第二cat
。
演示:
爲什麼會是這樣?字符串* first *中有一個匹配的'cat'。 –
這會改善你的問題,如果你想編輯它來解釋你認爲文檔中所說的交替意味着什麼。 –
我不確定你是否已經找到你需要的東西,但是,你可能想看看前瞻和後視 - http://www.regular-expressions.info/lookaround.html –