简体   繁体   English

通过模式查找所有事件并在Python中替换其中的引号

[英]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" 这是我要实现的,将以下"text example.. something + "hello" + foo"替换为: "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 : @EDIT我认为最好添加我的字符​​串的确切示例(我的字符串看起来类似于JSON

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

now I want to remove quotes from x like this: 现在我想像这样从x删除引号:

"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. 这将不匹配第一个和最后一个引号,仅匹配字符串中的那些。

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

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