2012-04-30 87 views
2

聲明:我知道「in」和「not in」可以使用,但由於技術上的限制,我需要使用正則表達式。正則表達式包含「時間」,但不包含「時鐘」

我:

a = "digital clock time fan. Segments featuring digital 24 hour oclock times. For 11+" 
b = "nine times ten is ninety" 

,我想匹配基於包含「時間」,而不是「點鐘」,所以A和B是通過正則表達式把只有B通過

任何想法?

回答

7

您可以使用此一negative lookahead

^(?!.*\bo?clock\b).*\btimes\b 

說明:

^     # starting at the beginning of the string 
(?!    # fail if 
    .*\bo?clock\b # we can match 'clock' or 'oclock' anywhere in the string 
)     # end if 
.*\btimes\b  # match 'times' anywhere in the string 

\b是單詞邊界,所以你還是會匹配像'clocked times'一個字符串,但會失敗的字符串像'timeshare'。如果你不想要這種行爲,你可以刪除正則表達式中的所有\b

例子:

>>> re.match(r'^(?!.*\bo?clock\b).*\btimes\b', a) 
>>> re.match(r'^(?!.*\bo?clock\b).*\btimes\b', b) 
<_sre.SRE_Match object at 0x7fc1f96cc718> 
+1

歡呼聲,這是偉大的! – rikAtee

+1

也適用於Java(我看到標有「python」的問題) –

相關問題