如何用匹配的转换替换重新匹配?


问题内容

例如,我有一个字符串:

The struct-of-application and struct-of-world

使用re.sub,它将用预定义的字符串替换匹配项。如何用匹配内容的转换替换匹配?要获取,例如:

The [application_of_struct](http://application_of_struct) and [world-of-struct](http://world-of-struct)

如果我编写了一个简单的正则表达式((\w+-)+\w+)并尝试使用re.sub,则似乎无法使用匹配的内容作为替换的一部分,更不用说编辑匹配的内容了:

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'
>>>