Regex to match string that does not have a preceding string

I'm using python to parse some files with multiple lines and perform regex using re.findall() .

I'm trying to match lines with the string "bar" as long as the string "no foo " is NOT in front of "bar". In other words - match any "bar" but do not match "no foo bar". If "bar" appears outside of the "no foo bar" then it should match.

Input:

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

Desired Output:

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

This is similar to the expression I have been trying but have not had any success:

(^|[^no foo ])bar

Code:

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/13454.html

上一篇: 在Python中转义正则表达式字符串

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