Python:如何对re的匹配字符串进行操作

Ado*_*obe 4 python regex coercion

下列

>>> re.sub(r'(\d+)', r'\1' * 2, 'test line 123')
Run Code Online (Sandbox Code Playgroud)

'test line 123123'
Run Code Online (Sandbox Code Playgroud)

有没有办法让它给

'test line 246'
Run Code Online (Sandbox Code Playgroud)

float() 胁迫不起作用:

>>> re.sub(r'(\d+)', float(r'\1') * 2, 'test line 123')
could not convert string to float: \1
Run Code Online (Sandbox Code Playgroud)

也不做evalexec.

Dor*_*mer 5

第二个参数re.sub()也可以是可调用的,它可以让你:

re.sub(r'(\d+)', lambda match:'%d' % (int(match.group(1))*2), 'test line 123')
Run Code Online (Sandbox Code Playgroud)

顺便说一句,确实没有理由使用float over int,因为你的正则表达式不包含句点而且总是一个非负整数