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

你可能感兴趣的:(json,爬虫,前端)