inserting \ in regular expressions

MRAB python at mrabarnett.plus.com
Wed Oct 26 18:38:37 EDT 2011


On 26/10/2011 20:48, Ross Boylan wrote:
> I want to replace every \ and " (the two characters for backslash and
> double quotes) with a \ and the same character, i.e.,
> \ ->  \\
> " ->  \"
>
> I have not been able to figure out how to do that.  The documentation
> for re.sub says "repl can be a string or a function; if it is a string,
> any backslash escapes in it are processed.That is, \n is converted to a
> single newline character, \r is converted to a carriage return, and so
> forth. Unknown escapes such as \j are left alone."
>
> \\ is apparently unknown, and so is left as is. So I'm unable to get a
> single \.
>
[snip]
The backspace character is also used for escaping in a regex, so you
need to escape it with a backslash:

 >>> print('Silly " quote or \\ backslash')
Silly " quote or \ backslash
 >>> print (re.sub(r'([\\\\"])', r"\\\1", 'Silly " quote or \\ backslash'))
Silly \" quote or \\ backslash



More information about the Python-list mailing list