Sandeep Sandeep - 1 year ago 60
Python Question

Python re replace group values

I have a regular expression through which I want to replace values with those values minus 10.
The re is:


I want to replace the x and y groups. To do this, I want to use
and passing it a function. However, in the function, how can I most easily build a string which is the same as the input, only with the x and y values replaced by themselves minus 10?

Answer Source

The re.sub docs show a good example of using a replacer function. In your case, this would work:

import re

def less10(string):
    return int(string) - 10

def replacer(match):
    return '%s%d,%d%s' % ('prefix'),

print re.sub(r'(?P<prefix><stuff[^>]*translate\()(?P<x>\d*),(?P<y>\d*)(?P<suffix>\)/>)',
             '<stuff translate(100,200)/>')