1

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?

Sandeep
  • 13
  • 6
  • Take a look at [this](http://stackoverflow.com/questions/2763750/how-to-replace-only-part-of-the-match-with-python-re-sub) answer for a cleaner way – FujiApple Aug 22 '16 at 02:43

1 Answers1

0

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

tony19
  • 125,647
  • 18
  • 229
  • 307
  • This, however, does not replace the new values into the string. I want to replace the input string with the same one with new x and y values but everything else the same. – Sandeep Aug 22 '16 at 01:15