如何用正则表达式替换字符串

时间:2021-08-01 08:28:21

标签: android json regex

我想从以下位置替换一个 json 字符串:

[{"id":151,"name":"me"}, {"id":4567432,"name":"you"}]

到:

[{"id":"151","name":"me"}, {"id":"4567432","name":"you"}]

如您所见,我只想为 id 的值(某个数字)添加括号。

我试过了:

json = json.replaceAll("\"id\",([0-9]+)", "\"id\",\"$1\"");

但它不起作用。我该怎么做?

2 个答案:

答案 0 :(得分:1)

您使用逗号作为键值分隔符,但在示例字符串中,您有一个冒号。

如果你使用,你可以修复 replaceAll 方法

replaceAll("(\"id\":)([0-9]+)", "$1\"$2\"")

参见online regex demo

详情

  • (\"id\":) - 第 1 组 ($1):"id": 字符串
  • ([0-9]+) - 第 2 组 ($2):一位或多位数字

答案 1 :(得分:0)

带有js代码

// #js code

const data = [{"id":151,"name":"me"}, {"id":4567432,"name":"you"}];

function solve1(data) {
  // solution 1
  // with stringify data
  const getMatches = data.match(/\"id\"\:\d+\,/gi);
  getMatches?.forEach((theMatch)=>{
    const getNumbers = theMatch.match(/\d+/gi).join("");
    const newMatch = theMatch.replace(getNumbers,`"${getNumbers}"`);
    data = data.replace(theMatch,newMatch)
  })
  return data;
}
function solve2(data) {

  // solution 2
  // with json data
  return data.map((item)=>{
    item.id = item.id.toString(); 
    return item;
  })
}
console.log(solve1(JSON.stringify(data)));
console.log(solve2(data))

相关问题