我正在使用python来解析多行的一些文件,并使用 re.findall()
执行正则表达式 .
我正在尝试将字符串与“bar”匹配,只要字符串“no foo”不在“bar”前面 . 换句话说 - 匹配任何“bar”但不匹配“no foo 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)
1 回答
你想要实现的目标被称为负面观察: