re.sub replacement text \-escapes woe

A

Alexander Schmolck

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
 
P

Peter Otten

Alexander said:
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)

Peter
 
P

Peter Otten

Peter said:
Alexander said:
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...

Peter
 
D

David M. Wilson

Alexander said:
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('\\ ', '\\')

re.escape? :)


David
 
A

Alexander Schmolck

Peter Otten said:
Peter said:
Alexander said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top