例如,我有一个字符串:
The struct-of-application and struct-of-world
Run Code Online (Sandbox Code Playgroud)
使用re.sub,它将用预定义的字符串替换匹配项。如何用匹配内容的转换替换匹配?要获取,例如:
The [application_of_struct](http://application_of_struct) and [world-of-struct](http://world-of-struct)
Run Code Online (Sandbox Code Playgroud)
如果我编写了一个简单的正则表达式((\w+-)+\w+)并尝试使用re.sub,则似乎无法使用匹配的内容作为替换的一部分,更不用说编辑匹配的内容了:
In [10]: p.sub('struct','The struct-of-application and struct-of-world')
Out[10]: 'The struct and struct'
Run Code Online (Sandbox Code Playgroud)
使用功能进行替换
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'
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1055 次 |
| 最近记录: |