Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #15016

Re: inserting \ in regular expressions

Date 2011-10-26 23:38 +0100
From MRAB <python@mrabarnett.plus.com>
Subject Re: inserting \ in regular expressions
References <1319658482.13425.9.camel@corn.betterworld.us>
Newsgroups comp.lang.python
Message-ID <mailman.2241.1319668792.27778.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: inserting \ in regular expressions MRAB <python@mrabarnett.plus.com> - 2011-10-26 23:38 +0100

csiph-web