1

I didn't find out yet how to substitute any text (with re.sub or str.replace) when the text to be inserted is a single backslash ( \ ).

I tried this:

import re

cad = 'random\\text'

re.sub(r"\\\\", "\\", cad)

but i got:

   raise error, v # invalid expression
error: bogus escape (end of line)

The pattern seems correct, as I checked on http://pythex.org/ The problem relies on the replacement. Any idea?

richar8086
  • 177
  • 4
  • 13
  • you didnt set your second string as a raw string so the pattern that the regex engine reads is just a single backspace which is invalid. ie for regex, `'\\\\\\\\' == r'\\\\'` – R Nar Nov 03 '15 at 23:35
  • but as @Ethan Bierlein stated, just use str.replace – R Nar Nov 03 '15 at 23:36
  • `"\\"` = `r"\"`. [*Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character)*](https://docs.python.org/2.0/ref/strings.html). – Wiktor Stribiżew Nov 03 '15 at 23:59

2 Answers2

1

There's no real need to use a regular expression here. You can simply use str.replace like this:

cad = cad.replace("\\\\", "\\")

The above should work.

Ethan Bierlein
  • 3,353
  • 4
  • 28
  • 42
0

For the regex to work, you need to use raw strings (r"" and r'') for all strings involving \

import re
cad = r'random\\text'
newCad = re.sub(r"\\\\", r"\\", cad)
Chris Redford
  • 16,982
  • 21
  • 89
  • 109
  • You have to escape backslash with a backslash. So my code *is* replacing two backslashes with one. Look at his original code and you will see that he knows this. All I did was add `r` to his original code. – Chris Redford Nov 03 '15 at 23:38
  • I'm running it in python right now and it is replacing two backslashes with one. Run it yourself. – Chris Redford Nov 03 '15 at 23:39
  • Okay, but using `re.sub` in this case is still not necessary. – Ethan Bierlein Nov 03 '15 at 23:42