您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python Regex子-使用Match作为替换中的Dict键

Python Regex子-使用Match作为替换中的Dict键

您可以传递一个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>'
python 2022/1/1 18:27:26 有187人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶