正则表达式在双引号内转义双引号 [英] Regular expression to escape double quotes within double quotes
本文介绍了正则表达式在双引号内转义双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串需要解析为JSON.
I have a string that needs to be parsed as JSON.
问题是,有时它可能包含双引号,从而导致解析错误.
The problem is, it may sometimes contain double quotes, causing errors in parsing.
例如:
{
"id_clients":"58844",
"id_clients_name" : ""100" test"qw"
}
我需要一个正则表达式来用\"
替换"
开头和结尾之间的所有双引号.
I need a regex to replace any double quotes between the opening and closing "
with a \"
.
谢谢.
推荐答案
我尝试了它只是为了好玩,尽管修复生成器肯定更好.这可能会适合您的情况,或者至少会激发您的灵感:
I tried it just for fun, even though it is certainly better to fix the generator. This might work in your case, or at least inspire you:
您可以在此处
$( function()
{
var myString = "{ \"na\"\"me\": \"va\"lue\", \"tes\"\"t\":\"ok\" }";
var myRegexp = /\s*\"([\w\"]+)\"\s*[,}:]/g;
var match;
var matches = [];
// Save all the matches
while((match = myRegexp.exec(myString)) !== null)
{
matches.push(match[1]);
console.log(match[1]);
}
// Process them
var newString = myString;
for (var i=0; i<matches.length; i++)
{
var newVal = matches[i].replace(/\"/g, '\\\"');
newString = newString.replace(matches[i], newVal);
}
alert(myString + "\n" + newString);
}
);
这篇关于正则表达式在双引号内转义双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文