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

时间:2016-07-11 17:22:09

标签: javascript regex

以下是我要匹配的html示例

/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq

我希望能够抓住:

<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>

但是我似乎无法弄清楚我需要使用的正则表达式。我找到了这样的例子:RegEx that will match the last occurrence of dot in a string。但我似乎无法适应我的用例。

编辑:应该已经指定...我想要匹配的事件将始终是最后一次出现。

1 个答案:

答案 0 :(得分:0)

You don't really need regular expressions for this. Assuming you have a container <div id="stuff"/> that wraps the code in the OP:

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

If you are using jQuery:

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

These selectors basically select the last <hr/> and <div/> tag children within <div id="stuff"/> and should be sufficient enough to grab those elements and do as you wish with them.