Python 正则表达式来匹配没有前面字符串的字符串
我正在使用python解析一些具有多行的文件,并使用Python 正则表达式来匹配没有前面字符串的字符串,python,regex,Python,Regex,我正在使用python解析一些具有多行的文件,并使用re.findall()执行正则表达式 只要字符串“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. fo
re.findall()
执行正则表达式
只要字符串“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
代码:
你试图实现的目标被称为消极的回头看:
for line in lines:
for match in re.findall('(?<!no foo )bar', line):
print('found "%s"' % str(line))
对于行中的行:
对于re.findall(')(?中的匹配,您试图实现的目标被称为消极落后:
for line in lines:
for match in re.findall('(?<!no foo )bar', line):
print('found "%s"' % str(line))
对于行中的行:
对于re.findall(‘)中的匹配,如果线条独特,则打印两次“no foo bar foo bar foo bar foo bar foo bar”。如果线条独特,则打印两次“no foo bar foo bar foo bar foo bar foo bar foo bar”。看起来像是大学一年级的练习或类似的东西