【问题标题】:How to replace string by regex如何用正则表达式替换字符串
【发布时间】:2021-10-07 01:06:48
【问题描述】:

我想从以下位置替换一个 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\"");

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

【问题讨论】:

  • "...我只想加括号..." 它们是双引号,不是括号。

标签: android json regex


【解决方案1】:

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

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

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

请参阅online regex demo

详情

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

【讨论】:

  • 哇,完美!国王! :)
【解决方案2】:

带有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))

【讨论】:

    猜你喜欢
    • 2018-07-13
    • 2015-11-30
    • 2021-11-29
    • 2017-02-04
    相关资源
    最近更新 更多