![](/img/trans.png)
[英]In Javascript Regex, how do I match hash tags, but not with the HTML code?
[英]How can I match a bunch of p tags at the end of an html document with javascript regex?
这是一个示例内容:
<p> so so so </p>
<div> whatever</div
<p> another paragraph </p>
<div> forever </div>
<p> first of last </p>
<p> second of last </p>
如何匹配上述文档末尾的最后两段(或任意数量的连续段落)?
我想要的匹配 output 是:
<p> first of last </p>
<p> second of last </p>
我试过/(<p>[\s\S]*?<\/p>[\s]*)$/g
,但是延迟匹配没有按预期工作,它吸收了所有 p 之间的标签,并且从它遇到的第一个开始 p 标记匹配到文档的末尾。
注意:末尾可能根本没有段落,如果末尾没有段落,则正则表达式不应该匹配。
这里我们使用正则表达式匹配所有段落,然后取结果数组的最后两个元素。
let str = `<p> so so so </p> <div> whatever </div <p> another paragraph </p> <div> forever </div> <p> first of last </p> <p> second of last </p>` let reg = /<p>[\w\s]*<\/p>/g; let res = str.match(reg); console.log(res[res.length-2]); console.log(res[res.length-1]);
添加负面展望以确保嵌套段落不匹配似乎可以解决问题:
/(<p>((??<p>)[\s\S])*?<\/p>[\s]*)+$/g
不过会感谢更好的建议!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.