-1

"TEXT&nbsp;<p>TEST1</p><br><div>&nbsp;<p>TEST2</p></div>" (string, not html)

Here i am trying to capture the last <p> tag until </p></div>. (Edit: NOT just the text between, I'm including the actual string tags)

How do you start from the end from where </p><div> is to the next prior <p> that contains "TEST2" instead of "TEST1"? I am running into this problem because the first match (going forwards) contains the match I am looking for, rather than being a separate match.

I know I can grab the index of the </p></div> and then loop backwards until I find a <p>, but this seems inefficient. I also know RegEx in JavaScript does not allow you to do search from end of string based on this answer (javascript regex search from end of string to begining) , so just posting because I am unaware of more optimal solutions.

Yu Mad
  • 828
  • 2
  • 12
  • 29
  • 2
    Possible duplicate of [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Obsidian Age Apr 26 '18 at 03:39

2 Answers2

1

Use negative look ahead:

<p>(?:.(?!<p>))+<\/div>

Similar question: Regex Last occurrence?

builder-7000
  • 7,131
  • 3
  • 19
  • 43
-1

var testStr='<p>TEST1</p><br><div>&nbsp;<p>TEST2</p></div>';
var matchesStr=testStr.match(/(\<[p]\>)(.|\;)*(\<\/p\>\<\/div\>){1}$/g);

// get your required result from array matchesStr 
console.log(matchesStr);

$('#matchResult').text(matchesStr.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="matchResult"></div>
Rudra
  • 11
  • 4