Python re.sub() : trying to replace escaped characters only

标签 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,我很感激对此的提示。

最佳答案

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

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/

相关文章:

python - PyCharm:Scapy Unresolved 引用

java - JLabel:重音字母问题

python - 同时训练两个模型

python - Tensorflow 在使用队列的 sess.run 调用上卡住

python - gcc : Unable to find Python. h, 当它在/usr/includes/python2.7 时?

正则表达式匹配大小写混合的单词

java - java.util.regex.Pattern.quote(String arg) 的 GWT 替代品是什么

删除字符串开头但不结尾的模式

c - strcmp() 不适用于 char *array 和 char const 比较

c++ - 循环向后打印字符串