1

I need to replace \ into \\ with python from pattern matching. For example, $$\a\b\c$$ should be matched replaced with $$\\a\\b\\c$$.

I couldn't use the regular expression to find a match.

>>> import re
>>> p = re.compile("\$\$([^$]+)\$\$")
>>> a = "$$\a\b\c$$"
>>> m = p.search(a)
>>> m.group(1)
'\x07\x08\\c'

I can't simply make the input as raw string such as a=r'$$\a\b\c$$' because it's automatically processed with markdown processor. I also found that I couldn't use replace method:

>>> a.replace('\\','\\\\')
'$$\x07\x08\\\\c$$'

How can I solve this issue?

prosseek
  • 182,215
  • 215
  • 566
  • 871
  • Do you have access to `a`'s initialization? If you do, try `a=r'$$\a\b\c$$'` (see http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l ) – Savir Nov 30 '14 at 21:54
  • @BorrajaX: No, it's a return value from the regular expression. – prosseek Nov 30 '14 at 21:59
  • Hmmmmpffrrr... Daang... Could you post the part that calculates that `a`? Once your string is evaluated, there's no way back (it doesn't know that `\x07` came from `\a`. Maybe something can be done before you get that `a`? – Savir Nov 30 '14 at 22:05
  • I found this answer (http://stackoverflow.com/a/18055356/289011 ) by the almighty Martijn Pieters. You're not gonna love it, though... but if he says so, that's probably right... – Savir Nov 30 '14 at 22:24

2 Answers2

2

The reason you're having trouble is because the string you're inputting is $$\a\b\c$$, which python translates to '$$\x07\x08\\c$$', and the only back slash in the string is actually in the segment '\c' the best way to deal with this would be to input a as such

a=r'$$\a\b\c$$'

This will tell python to convert the string literals as raw chars. If you're reading in from a file, this is done automatically for you.

ollien
  • 4,418
  • 9
  • 35
  • 58
0

Split the string with single backslashes, then join the resulting list with double backslashes.

s = r'$$\a\b\c$$'
t = r'\\'.join(s.split('\\'))
print('%s -> %s' % (s, t))
Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47