python正则表达式否定的lookahead断言

2024-03-29 07:01:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个cs新手,目前正致力于获得如下python正则表达式模式:

it must contain "stop (at most 10 words inbetween) mail" and do not contain "mail stop".

也就是说

^{pr2}$

我现在拥有的是:

import re
pattern = re.compile("(?=(stop\s+(\w+\s+){0,10}mail[^\s]*))(?!mail\s+stop)")
print(pattern.search("please stop the mail, I want the mail to stop").group())

但不知怎么的,它没有按我想要的方式工作。在

任何帮助都将不胜感激。在

埃里克


Tags: theremost模式itmailcsat
1条回答
网友
1楼 · 发布于 2024-03-29 07:01:03

假设您需要在匹配事件中返回整个输入字符串

>>> pattern = re.compile(".*stop\s+(\w+\s+){0,10}mail(?!(\s+stop|(.*mail stop))).*")
>>> print(pattern.search("please stop the mail, I want the mail to stop"))
<_sre.SRE_Match object at 0x15c43c0>
>>> print(pattern.search("please stop the mail stop"))
None
>>> print(pattern.search("please stop the mail, and I want the mail stop"))
None

相关问题 更多 >