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?

4
  • Do you have access to a's initialization? If you do, try a=r'$$\a\b\c$$' (see stackoverflow.com/questions/2081640/… ) Commented Nov 30, 2014 at 21:54
  • @BorrajaX: No, it's a return value from the regular expression. Commented Nov 30, 2014 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? Commented Nov 30, 2014 at 22:05
  • I found this answer (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... Commented Nov 30, 2014 at 22:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.