首页 > 解决方案 > 输入地标或如果不匹配 foo 字符串

问题描述

假设我有一个文件,例如:

tata toto
tata titi
tata

如果我正在制作像这样的正则表达式: ^(tata) (toto)?

如果找到 toto,我希望 \2=toto,否则 \2=foo

所以我想输出:

tata toto
tata foo
tata foo

正则表达式可以吗?

标签: pythonregex

解决方案


解决此问题的一种方法是用以下内容替换任何未tata跟随的toto内容tata foo

import re;

string = '''
tata toto
tata titi
tata
'''

print (re.sub('^tata(?! toto$).*$', 'tata foo', string, 0, re.M))

输出:

tata toto
tata foo
tata foo

推荐阅读