I need to apply regex replacement to a string in order to escape certain characters of a UNIX file path. In the original string I want to match a range of characters, and then replace it with the same character prepended with a backslash.
I'm trying to do this in the following way:
re.sub(r'([ \'\[\]])', r'\\\1', "./file to'escape.txt")
which, according to regex rules, should return ./file\ to\'escape.txt
, but instead it returns ./file\\ to\\'escape.txt
Other variants of the replacement string that I've tried don't work either:
r'\\1'
->./file\\1to\\1escape.txt
'\\\1'
->./file\\\x01to\\\x01escape.txt
'\\\\1'
->./file\\1to\\1escape.txt
'\\\\\1'
->./file\\\x01to\\\x01escape.txt
Is it possible at all to have an escaped backslash followed by a special sequence in python regex?