考虑以下字符串替换python代码:
import re
s = 'head abc.sys!0x1234 middle defg.sys!0x1a2b tail' # this could be potentially very long
d = {'0x1234' : 'Iamshorter',
'0x1a2b' : 'Iammuchlonger' }
pat = re.compile(r'(\w+.\w+)!(0x[\d\w]+)')
while True:
m = pat.search(s)
if not m:
break
module, addr = m.groups()
start, end = m.span()
s = s[:start] + '%s!%s' % (module, d[addr]) + s[end:]
print s
将输出
head abc.sys!Iamshorter middle defg.sys!Iammuchlonger tail
我正在寻找更快的python习惯用法,以便释放python正则表达式的强大功能。我尝试使用re.sub(),但我很难将'repl'作为匹配字符串的函数。任何建议都非常感谢。感谢。