2014-10-29 51 views
1

我试图构造一个正则表达式,如果字符串以 “艾萨克”开头,但如果是在某个地方“阿西莫夫的不匹配一致,即:Python的重新匹配,如果不串

"Isaac Peter bla hello" -> match 
"Isaac Peter bla Asimov hello" -> no match 

我的尝试是:

Isaac.*?(?!Asimov) 

从而未能让自己的正则表达式总是匹配(我不知道为什么) 任何想法?

+0

你是什么意思由* *失败? – dursk 2014-10-29 13:24:54

+1

这种情况不适用于'regex'。可以很容易地用字符串来完成。 – 2014-10-29 13:29:08

+0

失败我的意思是它匹配一切 – ProfHase85 2014-10-29 13:30:19

回答

3

使用下面的negative lookahead

^Isaac(?!.*?Asimov).*$ 

DEMO

>>> import re 
>>> s = """Isaac Peter bla hello 
... Isaac Peter bla Asimov hello""" 
>>> re.findall(r'(?m)^Isaac(?!.*?Asimov).*$', s) 
['Isaac Peter bla hello'] 

说明:

^      the beginning of the string 
Isaac     'Isaac' 
(?!      look ahead to see if there is not: 
    .*?      any character except \n (0 or more 
          times) 
    Asimov     'Asimov' 
)      end of look-ahead 
.*      any character except \n (0 or more times) 
$      before an optional \n, and the end of the 
         string 
+0

谢谢,有时我是一个傻瓜:) – ProfHase85 2014-10-29 13:29:09

+0

我们真的需要一个向前看吗?速度更快还是我的简单解决方案类似? – wenzul 2014-10-29 13:35:56

+0

@wenzul你的解决方案不提供我所需要的:你的解决方案与我需要的相反,我没有选择反转正则表达式,如果你对背景感兴趣,请看这里: http://docs.ansible .com/lineinfile_module.html 这个模块用正则表达式替换了一行,没有反选等选项 – ProfHase85 2014-10-29 13:38:54

1

或者没有正则表达式:

if str.startswith('Isaac') and 'Asimov' not in str: 
    # ... 
+0

我需要一个正则表达式(for ansible module;)) – ProfHase85 2014-10-29 13:29:31

0

如果你只需要匹配和不希望有您可以使用

import re 
>>> a="Isaac Peter bla hello" 
>>> b="Isaac Peter bla Asimov hello" 
>>> re.match(r"^Isaac.*Asimov.*$", a) 
>>> re.match(r"^Isaac.*Asimov.*$", b) 
<_sre.SRE_Match object at 0x0000000001D4E9F0> 

您可以轻松地反转匹配组...