捕获<pre> </pre>标签之间的所有内容

时间:2019-02-24 04:08:03

标签: javascript html regex

我正在阅读.html文件:

const htmlin = String(fs.readFileSync(inputHtml) || '');

const splitted = htmlin.split(/<pre.*>/);
splitted.shift();

const justPost = splitted.join('').split('</pre>');
justPost.pop();

但是我正在寻找一种匹配其中所有文本的方法

aaa <pre> xxx </pre> bbb <pre> foo </pre> ccc

,并匹配外面的文字。这样我就可以得到两个数组:

['aaa ', ' bbb ', ' ccc']

[' xxx ', ' foo ']

我该如何使用正则表达式或其他方法呢?

2 个答案:

答案 0 :(得分:3)

一种方法是使用正则表达式替换功能和捕获组。

<pre>(.*?)(?=<\/pre>)|(?:^|<\/pre>)(.*?)(?=$|<pre>)
  • <pre>(.*?)(?=<\/pre>)-在pre标签之间匹配文本。 (g1)
  • (?:^|<\/pre>)(.*?)(?=$|<pre>)-匹配pre标签中的文本。 (g2)

let str = `aaa <pre> xxx </pre> bbb <pre> foo </pre> ccc`
let inner = []
let outer = []

let op = str.replace(/<pre>(.*?)(?=<\/pre>)|(?:^|<\/pre>)(.*?)(?=$|<pre>)/g, function (match,g1,g2){
  if(g1){
    inner.push(g1.trim())
  } 
  if(g2){
    outer.push(g2.trim())
  }
  return match
})

console.log(outer)
console.log(inner)

答案 1 :(得分:1)

您可以使用dom或domparser代替正则表达式。

例如,创建一个div并将innerHTML属性设置为您的html。然后循环子节点并获取innerHTML或textContent。

例如:

let htmlString = `aaa <pre> xxx </pre> bbb <pre> foo </pre> ccc`,
  pre = [],
  text = [];
let div = document.createElement('div');
div.innerHTML = htmlString;

div.childNodes.forEach(x => {
  if (x.nodeType === Node.TEXT_NODE) {
    text.push(x.textContent.trim())
  }
  if (x.nodeName === "PRE") {
    pre.push(x.innerHTML.trim());
  }
});

console.log(pre);
console.log(text);

相关问题