您可以传递一个callable来re.sub
告诉它如何处理match对象。
s = re.sub(r'<(\w+)>', lambda m: replacement_dict.get(m.group()), s)
dict.get
如果说的字词不在替换字典中,则使用允许您提供“备用”,即
lambda m: replacement_dict.get(m.group(), m.group())
# fallback to just leaving the word there if we don't have a replacement
我会注意到,在使用re.sub
(和系列,即re.split
)时,指定所需替换 周围 存在的内容时,使用环顾四周表达式通常会更干净,以免匹配周围的内容被淡化。所以在这种情况下,我会像这样写你的正则表达式
r'(?<=<)(\w+)(?=>)'
否则,您必须在的括号中进行一些拼接/切入lambda
。为了弄清楚我在说什么,举一个例子:
s = "<soMetag>this is stuff<othertag>this is other stuff<closetag>"
d = {'othertag': 'blah'}
#this doesn't work because `group` returns the whole match, including non-groups
re.sub(r'<(\w+)>', lambda m: d.get(m.group(), m.group()), s)
Out[23]: '<soMetag>this is stuff<othertag>this is other stuff<closetag>'
#this output isn't exactly ideal...
re.sub(r'<(\w+)>', lambda m: d.get(m.group(1), m.group(1)), s)
Out[24]: 'soMetagthis is stuffblahthis is other stuffclosetag'
#this works, but is ugly and hard to maintain
re.sub(r'<(\w+)>', lambda m: '<{}>'.format(d.get(m.group(1), m.group(1))), s)
Out[26]: '<soMetag>this is stuff<blah>this is other stuff<closetag>'
#lookbehind/lookahead makes this nicer.
re.sub(r'(?<=<)(\w+)(?=>)', lambda m: d.get(m.group(), m.group()), s)
Out[27]: '<soMetag>this is stuff<blah>this is other stuff<closetag>'