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

需求:

我们有一个这样的字符串

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

需要提取里面的字符串

javascript 复制代码
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版本

相关推荐
IT_陈寒28 分钟前
Redis持久化丢失数据的坑,这次终于被我填平了
前端·人工智能·后端
独泪了无痕2 小时前
Lodash-JavaScript的实用工具库
前端·javascript
有趣的老凌2 小时前
用 Vibe Coding 搭了一个完整小程序「一定能成」
前端·javascript·后端
kyriewen12 小时前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_233314 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
天蓝色的鱼鱼16 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷17 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花17 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷17 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全