I am having a hard time in matching the string "\" with a regualar expression. I tried the following but it did not work.
print re.sub('([\"\\\\\"])', "-", myText, 0)
Any idea?
Thanks,
I am having a hard time in matching the string "\" with a regualar expression. I tried the following but it did not work.
print re.sub('([\"\\\\\"])', "-", myText, 0)
Any idea?
Thanks,
@iCodez is right, but if you really want to use regex:
>>> re.sub(r"\\", "-", r"this\and\that")
'this-and-that'
Note the use of r
to specify a raw string.
EDIT: Actually, re-reading your question it's not entirely clear whether you want to replace \
or "\"
- in the latter case, you'll want:
>>> re.sub(r'"\\"', "-", r'This "\" string "\" is "\" odd.')
'This - string - is - odd.'
... which, again as iCodes points out, is simpler with a straight replace()
:
>>> text = r'This "\" string "\" is "\" odd.'
>>> text.replace(r'"\"', '-')
'This - string - is - odd.'
Backslash serves as an escape character. For every single (\
) backslash you need two backslashes (\\
).
The use of r
is Python’s raw string notation for regular expression patterns and to avoid escaping.
>>> re.sub(r'"\\"', '-', r'foo "\" bar "\" baz')
'foo - bar - baz'
If you were just wanting to replace the backslash itself without the quotes around it.
>>> re.sub(r'\\', '-', r'foo\bar\baz')
'foo-bar-baz'
I think your regex needs some tweaking. If I understand what you are trying to do, you want to replace "\" with -.
print re.sub('\"\\\\\"', "-", myText, 0)