正则表达式来匹配没有前面字符串的字符串

我使用python来分析多行文件,并使用re.findall()执行regex。

只要字符串“no foo”不在“bar”之前,我正尝试将字符串与“bar”匹配。 换句话说 - 匹配任何“酒吧”,但不匹配“没有富酒吧”。 如果“bar”出现在“no foo bar”之外,那么它应该匹配。

输入:

1. candy bar 1
2. no bar stool
3. no foo bar here
4. foo barred
5. still no foo bar.
6. foo bar!
7. foobar!
8. tricky no foo bar but has bar again

期望的输出:

1. candy bar 1
2. no bar stool
4. foo barred
6. foo bar!
7. foobar!
8. tricky no foo bar but has bar again

这与我一直在尝试的表达方式类似,但没有取得任何成功:

(^|[^no foo ])bar

码:

patterns = ["XXX", "(^|[^no foo ])bar"]
joinedpatterns = "|".join(patterns)
for line in lines:
   for match in re.findall(joinedpatterns, line):
       print 'found "%s"' % str(match)

你试图实现的是所谓的负面后顾:

for line in lines:
    for match in re.findall('(?<!no foo )bar', line):
        print('found "%s"' % str(line))
链接地址: http://www.djcxy.com/p/13453.html

上一篇: Regex to match string that does not have a preceding string

下一篇: Python regex to match a specific word