正则表达式以在双引号内转义双引号

时间:2022-09-15 13:07:06

I have a string that needs to be parsed as JSON.

我有一个需要解析为JSON的字符串。

The problem is, it may sometimes contain double quotes, causing errors in parsing.

问题是,它有时可能包含双引号,导致解析错误。

For example:

例如:

{
    "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 \".

我需要一个正则表达式来替换打开和关闭之间的任何双引号“with a”。

Thanks.

谢谢。

2 个解决方案

#1


5  

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:

我试过它只是为了好玩,即使修理发生器肯定更好。这可能适用于您的情况,或至少激励您:

You can try it here

你可以在这里试试

$( 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);
}
);

#2


-1  

You can try, although this will work only for the opening tags :

您可以尝试,虽然这只适用于开始标记:

.replace(/\"\"/g, '\\""');

#1


5  

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:

我试过它只是为了好玩,即使修理发生器肯定更好。这可能适用于您的情况,或至少激励您:

You can try it here

你可以在这里试试

$( 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);
}
);

#2


-1  

You can try, although this will work only for the opening tags :

您可以尝试,虽然这只适用于开始标记:

.replace(/\"\"/g, '\\""');