re.sub replacement text \-escapes woe

Alexander Schmolck a.schmolck at gmx.net
Fri Feb 13 21:30:54 EST 2004


Peter Otten <__peter__ at web.de> writes:

> Peter Otten wrote:
> 
> > Alexander Schmolck wrote:
> > 
> >> Sorry if I missed something obvious, but how do you do this more
> >> intelligently?
> >> 
> >> def escape(s):
> >>     return re.sub(r'([${}\\])', r'\ \1', s).replace('\\ ', '\\')
> >> 
> >> 'as
> > 
> > Interesting. No direct attack, but another workaround:
> > 
> > re.sub(r'([${}\\])', lambda m: '\\' + m.group(), s)
> 
> re.sub(r'([${}\\])', r'\\\1', s)
> 
> Either that or I'm slash-blind tonight...

D'oh -- slash-blindness is what happened to me (presumably because I was
unconsciously expecting a raw string when I tested the above in the
interactive console before I posted and thus incorrectly dismissed the
result).

Thanks

'as



More information about the Python-list mailing list