Help with regular expression backreferences

Steve Purcell stephen_purcell at yahoo.com
Wed Mar 28 04:47:44 EST 2001


David Lees wrote:
> I would like to use regular expression back references as keys into a
> dictionary when doing substitution.  So far all I have is:
> 
> s='This xxMYJunkkxx the string that xxYourJunkxx the thing'
> p=re.compile(r'xx(\w+)xx')
> new_s=re.sub(p,'junk',s)
> print new_s

Don't use 're.sub' -- use the 'sub' method of your compiled regex 'p':

>>> import re
>>> s='This xxMYJunkkxx the string that xxYourJunkxx the thing'
>>> p=re.compile(r'xx(\w+)xx')
>>> new_s = p.sub(r'\1', s)
>>> new_s
'This MYJunkk the string that YourJunk the thing'


-Steve


-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo




More information about the Python-list mailing list