因为你有反斜杠前缀模式和替换 r : -
print re.sub(r'([a-zA-Z0-9\[\]\$\' ].*{).*(}[a-zA-Z\.,; ].*)',r'\1replace-string\2',line)
print re.sub(r'(.*{).*(}.*)', r'\1replace-string\2', line)
编辑:使用替换功能替换每第二次出现
import re
def repl(matchobj):
global counter
counter = counter+1
if counter == 2:
return '{replace-string}'
else:
return matchobj.group(0)
counter = 0
line = "$lang['MY_KEY'] = '{search-string} wird in Analyse {search-string} bercksichtigt'";
print re.sub(r'{.*?}',repl,line)
编辑:使用字典来存储替换
import re
def repl(matchobj):
global counter
replacementFor = {'{search-string1}': '{replace-string1}',
'{search-string2}': '{replace-string2}',
'{search-string3}': '{replace-string3}'}
counter = counter+1
if counter == 2:
return replacementFor.get(matchobj.group(0), matchobj.group(0))
else:
return matchobj.group(0)
counter = 0
line = "$lang['MY_KEY'] = '{search-string} wird in Analyse {search-string1} bercksichtigt'";
print re.sub(r'{.*?}',repl,line)
counter = 0
line = "$lang['MY_KEY'] = '{search-string} wird in Analyse {search-string3} bercksichtigt'";
print re.sub(r'{.*?}',repl,line)