![](/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.