简体   繁体   中英

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

Here is a sample of the html I am trying to match

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

I want to be able to grab:

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

However I cannot seem to figure out the regex I need to use. I have found examples such as this: RegEx that will match the last occurrence of dot in a string . But I cannot seem to adapt that to my use case.

EDIT: Should have specified...the occurrence I am trying to match will always be the last occurrence.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM