简体   繁体   中英

Find all occurences by pattern and replace quotes within it in Python

I want to replace quotes " with \\" inside quotes in my long String. So, I came up with idea to find it by pattern and then replace those quotes. But what I'm missing is probably wrong pattern or wrong method usage:

string = re.sub(r"\"(.*)\"",  r"\1", string).re.replace("\"", "\\\"")

Unfortunately it still replaces all quotes instead of those inside.

This is what I want to achieve, replace this "text example.. something + "hello" + foo" to this: "text example.. something + \\"hello\\" + foo"

Note, that this can occur many times in my long string. Thanks for any kind of advice! :)

@EDIT I think it is better to add the exact example of my string (my string looks similar to JSON :

"data": "fun () { return this.value * 20 + "x"; }"

now I want to remove quotes from x like this:

"data": "fun () { return this.value * 20 + \\"x\\"; }"

Try using negative lookaround :

(?<!^)\"(?!$)

See this demo .

This won't match the first and the last quotes, only those inside the string.

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