简体   繁体   中英

Replace single quotes in a string but not escaped single quotes

I'm making a Python API get request and getting JSON results which I have captured in a string. The string is similar to a string literal containing a dictionary: {'key1': 4, 'key2': 'I\\'m home'} . I need to format it to a string literal containing a proper JSON object like this: {"key1": 4, "key2": "I\\'m home"} , so that I can save to a JSON file.

To achieve this, I tried using regular expressions with negative look-ahead to replace all the single quotes (except the escaped single quote) like this:

import re

#.... other codes
str = re.sub("'(!?\')", "\"", result) # result = "{'key1': 4, 'key2': 'I\'m home'}"
print (str)

But I get this output

{"key1": 4, "key2": "I"m home"}

instead of

{"key1": 4, "key2": "I\'m home"}

How do I create the regular expression, so that escaped single quotes \\' are preserved and all others are replaced with double-quotes.

You need a negative lookbehind, not a negative lookahead ("no backslash before a quote"):

result = '''{'key1': 4, 'key2': 'I\\'m home'}'''
print(re.sub(r"(?<!\\)'", '"', result))
#{"key1": 4, "key2": "I\'m home"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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