Python re.sub():仅尝试替换转义字符

时间:2019-10-30 17:48:15

标签: python regex string replace

使用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,那么我对此表示感谢。

2 个答案:

答案 0 :(得分:1)

首先,您需要使用原始字符串来分配text,以便反斜杠将按字面意义保留(或者可以转义反斜杠)。

text = r'These are "quotes", and these are \"escaped quotes\"'

第二,您需要在正则表达式中转义反斜杠,以便正则表达式引擎将其按字面意义处理。

print(re.sub(r'\\"', '~', text))

答案 1 :(得分:0)

使用原始文本可能会有所帮助。

import re

text = r'These are "quotes", and these are \"escaped quotes\"'
print(re.sub(r'\\"', '~', text))