Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #15016 > unrolled thread
| Started by | MRAB <python@mrabarnett.plus.com> |
|---|---|
| First post | 2011-10-26 23:38 +0100 |
| Last post | 2011-10-26 23:38 +0100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: inserting \ in regular expressions MRAB <python@mrabarnett.plus.com> - 2011-10-26 23:38 +0100
| From | MRAB <python@mrabarnett.plus.com> |
|---|---|
| Date | 2011-10-26 23:38 +0100 |
| Subject | Re: inserting \ in regular expressions |
| Message-ID | <mailman.2241.1319668792.27778.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web