簡體   English   中英

正則表達式以在雙引號內轉義雙引號

[英]Regular expression to escape double quotes within double quotes

我有一個需要解析為JSON的字符串。

問題是,它有時可能包含雙引號,導致解析錯誤。

例如:

{
    "id_clients":"58844",

    "id_clients_name" : ""100" test"qw"
}

我需要一個正則表達式來替換打開和關閉之間的任何雙引號" with a \\"

謝謝。

我嘗試它只是為了好玩,即使修理發生器肯定更好。 這可能適用於您的情況,或至少激勵您:

你可以在這里試試

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

您可以嘗試,雖然這只適用於開始標記:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM