/ / Python Regex Negative Lookahead-Behauptung - Python, Regex

Python Regex negative Lookahead Assertion - Python, Regex

Ich bin ein Cs-Neuling und arbeite derzeit daran, ein Python-Regex-Muster wie das folgende zu erhalten:

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

das heißt,

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

Was ich derzeit habe, ist:

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

aber irgendwie funktioniert es nicht so wie ich es will.

Jede Hilfe wäre willkommen.

Eric

Antworten:

1 für die Antwort № 1

Angenommen, Sie müssen die gesamte Eingabezeichenfolge im Falle einer Übereinstimmung zurückgeben

>>> pattern = re.compile(".*stops+(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