Sandeep Sandeep - 3 months ago 9
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:

re.compile(r'<stuff[^\>]*translate\((?P<x>\d*),(?P<y>\d*)\)"/>')


I want to replace the x and y groups. To do this, I want to use
re.sub
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

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' % (match.group('prefix'),
                          less10(match.group('x')),
                          less10(match.group('y')),
                          match.group('suffix'))

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

http://ideone.com/tQS4wK