正则表达式包含“时间”但不包含“时钟”

时间:2012-04-30 22:59:11

标签: python regex

免责声明:我知道“in”和“not in”可以使用,但由于技术限制,我需要使用正则表达式。

我有:

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

我希望匹配基于包含“时间”而不是“oclock”,所以a和b通过正则表达式而且只有b通过

有什么想法吗?

1 个答案:

答案 0 :(得分: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>