Python中如何用正则或replace处理带引号的字符串替换?
解决方案
- 若使用JavaScript,可通过
replace()结合全局正则表达式批量替换所有title字段内的目标内容:// 原始转义后的JSON字符串 const originalStr = '[{"title": "something with {\"}", "pub_year": 1988}, {"title": "something with {\"}", "pub_year": 1988}]'; // 全局替换"something with {"为"something without {" const modifiedStr = originalStr.replace(/"title": "something with \{"/g, '"title": "something without \{'); console.log(modifiedStr); - 若你的字符串是HTML转义格式(含
"),直接针对转义内容写正则即可:const htmlEscapedStr = '"[{"title": "something with {"}", "pub_year": 1988}, {"title": "something with {"}", "pub_year": 1988}]"'; const modifiedHtmlStr = htmlEscapedStr.replace(/"title": "something with \{"/g, '"title": "something without \{"'); console.log(modifiedHtmlStr); - 用Python实现的话,借助
re.sub()完成全局替换:import re original_str = '[{"title": "something with {\"}", "pub_year": 1988}, {"title": "something with {\"}", "pub_year": 1988}]' modified_str = re.sub(r'"title": "something with \{', '"title": "something without \{', original_str) print(modified_str)
内容的提问来源于stack exchange,提问作者Alen
相关产品推荐
相关产品推荐

