繁体   English   中英

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

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

使用 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 function 的“无效”JSON 文件,并按原样放置换行符。 如果有更简单的方法来解析 JSON 与键值中的换行符,我很感激这方面的提示。

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

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

其次,您需要转义正则表达式中的反斜杠,以便正则表达式引擎按字面意思处理它。

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

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

import re

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM