4

I'm trying to use re.sub on a string with a numeric value directly after a numeric backreference. That is, if my replacement value is 15.00 and my backreference is \1, my replacement string would look like:

\115.00, which as expected will throw an error: invalid group reference because it thinks my backreference group is 115.

Example:

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)

Is there a solution that doesn't involve more than re.sub?

atp
  • 27,422
  • 41
  • 120
  • 179

1 Answers1

6

Use an unambiguous backreference syntax \g<1>. See re.sub reference:

\g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'.

See 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
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • 1
    Thanks! I thought there must be some more precise backreference syntax, but didn't know which. – atp Jun 27 '16 at 22:14
  • Thanks, but note that `\g<1>` syntax only works in the `repl` argument of `re.sub` as the docs say! I had to unambiguously refer to a backreference within the search-pattern itself. The solution was to use named groups: `r"(?P[1-9])0\d(?P=x)0\d"` which captures the group as name "x" and then looks for a repetition of that value. The first part of my string is the capture and the second is the re-use. – Mitch McMabers Nov 16 '19 at 20:37
  • @MitchMcMabers The `(?P=x)` is an *inline backreference* used in the regex pattern while this answer and question are about *replacement backreferences* used in the replacement pattern. – Wiktor Stribiżew Nov 16 '19 at 23:24
  • @WiktorStribiżew Yeah, but I added my comment because this is the first Google result for how to add numbers after backreferences. Now both types of visitors will find the technique they need for their backreferences! :) – Mitch McMabers Nov 19 '19 at 21:24
  • @MitchMcMabers I doubt it will help a lot of visitors, the question is marked as a dupe and there is an automatic redirect for those who are not SO users to the original question. – Wiktor Stribiżew Nov 19 '19 at 21:50