使用正则提取字符串中的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版本

相关推荐
祝余呀3 分钟前
HTML初学者第三天
前端·html
就爱瞎逛19 分钟前
TailWind CSS Intellisense 插件在VSCode 上不生效
前端·css·vscode·tailwind
柚子81622 分钟前
sibling-index:我用这个画时钟表盘
前端·css
UI设计和前端开发从业者37 分钟前
UI前端大数据处理策略优化:基于云计算的数据存储与计算
前端·ui·云计算
前端小巷子1 小时前
Web开发中的文件上传
前端·javascript·面试
翻滚吧键盘2 小时前
{{ }}和v-on:click
前端·vue.js
上单带刀不带妹2 小时前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
杨进军2 小时前
React 创建根节点 createRoot
前端·react.js·前端框架
ModyQyW3 小时前
用 AI 驱动 wot-design-uni 开发小程序
前端·uni-app
说码解字3 小时前
Kotlin lazy 委托的底层实现原理
前端