【问题标题】:python regex negative lookahead assertionpython 正则表达式否定前瞻断言
【发布时间】:2012-07-24 09:03:10
【问题描述】:

我是一名 cs 新手,目前正在努力获得这样的 python 正则表达式模式:

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

也就是说,

  "please stop the mail, and I want the mail stop" AND "please stop the mail stop" would be rejected. ("mail stop" pattern spotted)


  "please stop the mail" AND "please stop the mail, I want the mail to stop" both would be accepted.(only "stop ~ mail" pattern is seen, and no "mail stop")

我目前拥有的是:

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())

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

任何帮助将不胜感激。

埃里克

【问题讨论】:

  • 您想将输入的哪一部分捕获到group()

标签: python regex


【解决方案1】:

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

>>> 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 2020-04-15
    • 2013-08-19
    • 1970-01-01
    • 2018-12-28
    • 2012-04-14
    • 1970-01-01
    相关资源
    最近更新 更多