如何用该匹配的转换替换重新匹配? [英] How to replace an re match with a transformation of that match?
本文介绍了如何用该匹配的转换替换重新匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一个字符串:
For example, I have a string:
The struct-of-application and struct-of-world
使用re.sub
,它将用预定义的字符串替换匹配的字符串.如何用匹配内容的转换替换匹配?获取,例如:
With re.sub
, it will replace the matched with a predefined string. How can I replace the match with a transformation of the matched content? To get, for example:
The [application_of_struct](http://application_of_struct) and [world-of-struct](http://world-of-struct)
如果我写一个简单的正则表达式 ((\w+-)+\w+)
并尝试使用 re.sub
,似乎我不能使用我的匹配作为替换的一部分,更不用说编辑匹配的内容了:
If I write a simple regex ((\w+-)+\w+)
and try to use re.sub
, it seems I can't use what I matched as part of the replacement, let alone edit the matched content:
In [10]: p.sub('struct','The struct-of-application and struct-of-world')
Out[10]: 'The struct and struct'
推荐答案
使用 替换函数
s = 'The struct-of-application and struct-of-world'
p = re.compile('((\w+-)+\w+)')
def replace(match):
return 'http://{}'.format(match.group())
#for python 3.6+ ...
#return f'http://{match.group()}'
>>> p.sub(replace, s)
'The http://struct-of-application and http://struct-of-world'
>>>
这篇关于如何用该匹配的转换替换重新匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文