python在正则表达式中匹配"\"

Ste*_*ano 0 python regex

我很难将字符串"\"与一个regualar表达式匹配.我试过以下但是没有用.

print re.sub('([\"\\\\\"])', "-", myText, 0)
Run Code Online (Sandbox Code Playgroud)

任何的想法?

谢谢,

Zer*_*eus 5

@iCodez是对的,但如果你真的想使用正则表达式:

>>> re.sub(r"\\", "-", r"this\and\that")
'this-and-that'
Run Code Online (Sandbox Code Playgroud)

注意r用于指定原始字符串.

编辑:实际上,重新阅读你的问题并不完全清楚你是否想要替换\"\"- 在后一种情况下,你会想要:

>>> re.sub(r'"\\"', "-", r'This "\" string "\" is "\" odd.')
'This - string - is - odd.'
Run Code Online (Sandbox Code Playgroud)

...再次像iCodes指出的那样,直线更简单replace():

>>> text = r'This "\" string "\" is "\" odd.'
>>> text.replace(r'"\"', '-')
'This - string - is - odd.'
Run Code Online (Sandbox Code Playgroud)