您可以在使用
re.finditer()
:
# set of replacement rules
expl_table = [
(r'program.env\[(\d+)\]' , r'program_env_dsdsds\1'),
(r'program.local\[(\d+)\]', r'program_local_\1'),
]
declarations = []
for props in expl_table:
(re_from, re_to) = props
offset = 0
for m in re.finditer(re_from, string):
sub = m.expand(re_to)
string = string[:m.start()+offset] + sub + string[m.end()+offset:]
offset = max(map(len, [sub, m.group(0)])) - min(map(len, [sub, m.group(0)]))
declarations.append(sub)
print(string)
或者,可以“升级”同一范围内的lambda函数。通常,不允许在lambda函数中使用多个语句,但是列表理解稍微绕过了这个约束:
for props in expl_table:
(re_from, re_to) = props
string = re.sub(re_from,
lambda m: [
(result, declarations.append(result))
for result in [m.expand(re_to)]
][0][0],
string)
print(string)
print(declarations)