Using re
module it's possible to use escaping for the replace pattern. eg:
def my_replace(string, src, dst):
import re
return re.sub(re.escape(src), dst, string)
While this works for the most-part, the dst
string may include "\\9"
for example.
This causes an issue:
\\1
,\\2
... etc indst
, literals will be interpreted as groups.- using
re.escape(dst)
causes.
to be changed to\.
.
Is there a way to escape the destination without introducing redundant character escaping?
Example usage:
>>> my_replace("My Foo", "Foo", "Bar")
'My Bar'
So far, so good.
>>> my_replace("My Foo", "Foo", "Bar\\Baz")
...
re.error: bad escape \B at position 3
This tries to interpret \B
as having a special meaning.
>>> my_replace("My Foo", "Foo", re.escape("Bar\\Baz"))
'My Bar\\Baz'
Works!
>>> my_replace("My Foo", "Foo", re.escape("Bar\\Baz."))
'My Bar\\Baz\\.'
The .
gets escaped when we don't want that.
While in this case str.replace
can be used, the question about destination string remains useful since there may be times we want to use other features of re.sub
such as the ability to ignore case.