2017-07-24 78 views
1

我正在寫一個Python腳本,它在文本中查找一個短語(1到5個單詞)。 我想讓其他單詞成爲我正在尋找的短語之一,並且我試圖使用正則表達式來完成此類任務。使用正則表達式匹配特定的其他詞

說我的一句話就是

p = "red blue green" 

,我想允許只有一個別的名字,是其中的,還是把比賽:

t1 = "this is a red blue green flower"應該是匹配

t2 = "this is a red blue yellow green flower"應是一場比賽

t3 = "this is a red violet blue yellow green flower"應該是一場比賽

t4 = "this is a red blue yellow and green flower"不應該匹配

這是哪個正則表達式?

+0

或者不're':'任何(W在t用於phrase.split()中的w)。 –

+0

@MosesKoledoye也會匹配這個:「這是紅色的foo酒吧foo藍色酒吧綠色」 –

+0

你想檢查這些單詞的發生並忽略單詞'和'?可以很好,如果你可以提供2個更多的測試用例不匹配 –

回答

0

這裏有一種方式來獲得相應的正則表達式模式如果訂單red, blue, green始終推崇:

markers = "red blue green".split() 

pattern = r'\b'+ ' (\w+)?'.join(markers) + r'\b' 
print(pattern) 
# \bred (\w+)?blue (\w+)?green\b 

這裏有一個小測試:

t1 = "this is a red blue green flower" 
t2 = "this is a red blue yellow green flower" 
t3 = "this is a red violet blue yellow green flower" 
t4 = "this is a red blue yellow and green flower" 

import re 
print(re.search(pattern, t1)) 
# <_sre.SRE_Match object at 0x7ff0a72741c8> 
print(re.search(pattern, t2)) 
# <_sre.SRE_Match object at 0x7ff0a72741c8> 
print(re.search(pattern, t3)) 
# <_sre.SRE_Match object at 0x7ff0a72741c8> 
print(re.search(pattern, t4)) 
# None 
+0

謝謝,這是完美的! – Fed

相關問題