2012-04-30 88 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”的问题) –

相关问题