Javascript 正则表达式,用于匹配从最后一次出现的模式到跨多行的不同模式

Javascript regex to match from the last occurrence of pattern until a different pattern across multiple lines

本文关键字:模式 用于 正则表达式 最后一次 Javascript      更新时间:2023-09-26

这是我尝试匹配的html示例

<div><p>Hello World</p></div>
<hr style="margin: 10px">
<div><p>Regex is hard</p></div>

<div><p>Hello World</p></div>
<hr style="margin: 10px">
<div><p>Regex is hard</p></div>

<div><p>Block I want to Match</p></div>
<hr style="margin: 10px">
<div><p>Matching Text</p></div>

我希望能够抓住:

<hr style="margin: 10px">
<div><p>Matching Text</p></div>

但是,我似乎无法弄清楚我需要使用的正则表达式。我找到了这样的例子:RegEx 将与字符串中最后一次出现的点匹配。但我似乎无法将其适应我的用例。

编辑:应该指定...我尝试匹配的匹配项将始终是最后一个出现项。

你真的不需要正则表达式。假设您有一个将代码包装在 OP 中的容器<div id="stuff"/>

document.querySelectorAll('#stuff > hr:nth-last-of-type(1), #stuff > div:nth-last-of-type(1)');

如果您使用的是 jQuery:

$('#stuff > hr:nth-last-of-type(1), #stuff > div:nth-last-of-type(1)');

这些选择器基本上选择最后的<hr/>,并在<div id="stuff"/><div/>标记子元素,并且应该足以抓取这些元素并随心所欲地使用它们。