2012-07-23 69 views
0

我是CS新手,我目前正在得到這樣的蟒蛇正則表達式模式:蟒蛇正則式斷言

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

但不知何故,它不會按我想要的方式工作。

任何幫助,將不勝感激。

埃裏克

+0

什麼部分的情況下,要返回? – 2012-07-23 22:02:27

回答

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

感謝您的解決方案,它就像一個魅力! – EricSRK 2012-07-24 17:38:16