使用 Python 3.x,我需要用一些自定义模式替换某些文本中的转义双引号,并按原样保留非转义双引号。所以我写了一些简单的代码:
text = 'These are "quotes", and these are \"escaped quotes\"'
print(re.sub(r'\"', '~', text))
并期望看到:
These are "quotes", and these are ~escaped quotes~
但是我得到的不是上面的结果:
These are ~quotes~, and these are ~escaped quotes~
那么,仅替换转义引号的正确模式是什么?
此问题的背景是尝试读取其中包含 Javascript 函数的“无效”JSON 文件,该文件按原样放置换行符,但带有转义引号。如果有更简单的方法来解析键值中包含换行符的 JSON,我很感激对此的提示。
最佳答案
首先,您需要使用原始字符串来分配文本
,以便反斜杠将按字面保留(或者您可以转义反斜杠)。
text = r'These are "quotes", and these are \"escaped quotes\"'
其次,您需要转义正则表达式中的反斜杠,以便正则表达式引擎按字面意思处理它。
print(re.sub(r'\\"', '~', text))
关于Python re.sub() : trying to replace escaped characters only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58631109/