反向引用后直接的数字值

时间:2016-06-27 22:08:13

标签: python regex

我尝试在数字反向引用后直接对带有数值的字符串使用re.sub。也就是说,如果我的替换值是15.00而我的反引用是\1,那么我的替换字符串将如下所示:

\115.00,正如预期的那样会抛出error: invalid group reference,因为它认为我的后向引用组是115

示例:

import re

r = re.compile("(Value:)([-+]?[0-9]*\.?[0-9]+)")

to_replace = "Value:0.99" # Want Value:1.00

# Won't work:
print re.sub(r, r'\11.00', to_replace)

# Will work, but don't want the space
print re.sub(r, r'\1 1.00', to_replace)

是否有一种解决方案不超过re.sub

1 个答案:

答案 0 :(得分:6)

使用明确的反向引用语法\g<1>。请参阅re.sub参考:

  

\g<number>使用相应的组号;因此,\g<2>相当于\2,但在\g<2>0等替换中并不含糊。 \20将被解释为对组20的引用,而不是对组2的引用,后跟文字字符“0”。

请参阅this regex demo

Python demo

import re
r = re.compile("(Value:)([-+]?[0-9]*\.?[0-9]+)")
to_replace = "Value:0.99" # Want Value:1.00
print(re.sub(r, r'\g<1>1.00', to_replace))
# => Value:1.00