使用正则提取字符串中的json数据

需求:

我们有一个这样的字符串

`以下数据:{"title": "标题一", "text": "内容一", "tag": "tag1"}{"title": "标题二", "text": "内容二", "tag": "tag二"}`

需要提取里面的字符串

function extractDataFromString(str) {
  const regexTitle = /"title": "(.*?)"/g;
  const regexText = /"text": "(.*?)"/g;
  const regexTag = /"tag": "(.*?)"/g;

  let titles = [];
  let texts = [];
  let tags = [];

  let match;
  while ((match = regexTitle.exec(str))) {
    titles.push(match[1]);
  }

  while ((match = regexText.exec(str))) {
    texts.push(match[1]);
  }

  while ((match = regexTag.exec(str))) {
    tags.push(match[1]);
  }

  let result = [];

  for (let i = 0; i < titles.length; i++) {
    let obj = {
      title: titles[i],
      text: texts[i] || "",
      tag: tags[i] || ""
    };

    result.push(obj);
  }

  return JSON.stringify(result);
}

const jsonData = extractDataFromString(inputString);
console.log(jsonData);

golang版本

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值