我正试图构造一个正则表达式,如果字符串以“艾萨克”开头,则该表达式与之匹配,但如果字符串中有“Asimov”,则不匹配,即:
"Isaac Peter bla hello" -> match
"Isaac Peter bla Asimov hello" -> no match我的尝试是:
Isaac.*?(?!Asimov)这是失败的,所以我的正则表达式总是匹配(我不知道为什么),任何想法?
发布于 2014-10-29 13:26:29
使用如下所示的负前瞻。
^Isaac(?!.*?Asimov).*$演示
>>> 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发布于 2014-10-29 13:26:44
或者,没有regex:
if str.startswith('Isaac') and 'Asimov' not in str:
# ...发布于 2014-10-29 13:29:05
如果您只需要匹配,并且不想拥有可以使用的组
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>你可以很容易地倒置火柴..。
https://stackoverflow.com/questions/26631551
复制相似问题