Python:如何在re';s匹配字符串

Python:如何在re';s匹配字符串,python,regex,coercion,Python,Regex,Coercion,以下 >>> re.sub(r'(\d+)', r'\1' * 2, 'test line 123') 给予 'test line 123123' 有没有办法让它放弃 'test line 246' ? float()强制无效: >>> re.sub(r'(\d+)', float(r'\1') * 2, 'test line 123') could not convert string to float: \1 也不要eval或exec技巧是将函数作

以下

>>> re.sub(r'(\d+)', r'\1' * 2, 'test line 123')
给予

'test line 123123'
有没有办法让它放弃

'test line 246'
?

float()
强制无效:

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

也不要
eval
exec

技巧是将函数作为
repl
参数提供给:

每个匹配项都将转换为
浮点
,加倍,然后使用适当的格式转换为字符串

如果数字是整数,这可以简化一点,但是您的问题特别提到了
float
,所以我使用了它。

的第二个参数也可以是可调用的,它允许您执行以下操作:

re.sub(r'(\d+)', lambda match:'%d' % (int(match.group(1))*2), 'test line 123')
顺便说一句,没有理由使用float-over-int,因为正则表达式不包含句点,并且始终是非负整数

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