How to find values in string, manipulate and replace them
How to find values in string, add specific value to each of them and replace output with fixed string.
import re
def _replace(content):
#x = float(content.group(4))+20
#y = float(content.group(6))+20
return content.group(6)
print re.sub('<g(\s)transform="matrix\((.*)(\s)(.*)(\s)(.*)\)\"', _replace, '<g transform="matrix(0.412445 -0.0982513 0.0982513 0.412445 -5.77618 6开发者_如何学运维7.0025)">')
First off, I should repeat the usual warning about not parsing XML with regexes. It's a bad idea, and it will never work for all cases. If you're actually trying to parse the full xml document, use an XML parser.
That having been said, I'm guilty of doing quick and dirty stuff like this all the time. If you really just need a one-off solution, a simple regex can often get the job done. Just be aware that it will come back to haunt you as soon as you run into something more complex!
Next, I confess to not being much of a regex wiz, but here's how I'd modify your code snippet:
import re
def _replace(content):
values = [float(val) for val in content.group(2).split()]
values[3] += 20
values[5] += 100
values = ['{0}'.format(val) for val in values]
return content.group(1) + ' '.join(values) + content.group(3)
test_string = '<g transform="matrix(0.412445 -0.0982513 0.0982513 0.412445 -5.77618 67.0025)">'
pattern = r'(transform=\"matrix\()(.*?)(\))'
print test_string
print re.sub(pattern, _replace, test_string)
精彩评论