How to use python regular expression to substitute string value

Crutcher crutcher at gmail.com
Sun Feb 26 14:02:10 EST 2006


You don't really need regexes for this.

Assuming there is no whitespace in any of your values, it should be
really easy to parse the string.

s = 'x:11 y:0 w:760 h:19 area:14440 areaPerCent:0
totalAreaPerCent:-3.08011e+16 type:3 path:///-/1/1'

s.split() # break the string on whitespace
> ['x:11', 'y:0', 'w:760', 'h:19', 'area:14440', 'areaPerCent:0', 'totalAreaPerCent:-3.08011e+16', 'type:3', 'path:///-/1/1']

[ t.split(':',1) for t in s.split() ] # break each term on the first
':'
> [['x', '11'], ['y', '0'], ['w', '760'], ['h', '19'], ['area', '14440'], ['areaPerCent', '0'], ['totalAreaPerCent', '-3.08011e+16'], ['type', '3'], ['path', '///-/1/1']]

d = dict([ t.split(':',1) for t in s.split() ]) # make a dict of the
list
> {'type': '3', 'area': '14440', 'h': '19', 'w': '760', 'areaPerCent': '0', 'y': '0', 'x': '11', 'path': '///-/1/1', 'totalAreaPerCent': '-3.08011e+16'}

Now you can do this:
new_s = 'rect x="%(x)s" y="%(y)s" width="%(w)s" height="%(h)s"' % d
> 'rect x="11" y="0" width="760" height="19"'




More information about the Python-list mailing list