gpt4 book ai didi

python - 正则表达式包含 "times"但不包含 "clock"

转载 作者:行者123 更新时间:2023-11-28 20:51:15 25 4
gpt4 key购买 nike

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

我有:

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

我想根据包含“times”而不是“oclock”进行匹配,所以 a 和 b 通过正则表达式,只有 b 通过

有什么想法吗?

最佳答案

您可以使用 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>

关于python - 正则表达式包含 "times"但不包含 "clock",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10391635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com