Okay, here we go!
(?s)<(\w+)[^>]*\sclass="[^"]*"[^>]*>(?:(?!</?\1\b|<\w+[^>]*\sclass="[^"]*"[^>]*>)(?:Text i know()|.))*</\1>\2
The usual way to match just one of an element whose name is not know in advance is (we'll assume the (?s)
from here on):
<(\w+)[^>]*>(?:(?!</?\1\b).)*</\1>
The lookahead - (?!</?\1\b)
- prevents the dot from matching if it happens to be the first character of a tag (opening or closing) with the same name as the element you're currently matching. In this case a class
attribute is required too, so the first part becomes:
<(\w+)[^>]*\sclass="[^"]*"[^>]*>
The question wasn't prefectly clear on this, but I'm assuming you want to match the most immediate enclosing element with a class
attribute. That is, in the following text, you want to match the td.yes-me
element, not the table
element.
<table class="not-me">
<td class="not-me-either">
<p>Text i dont know</p>
</td>
<td class="yes-me">
<p>Text i dont know</p>
<p>Text i know</p>
<p>Text i dont know</p>
</td>
<td>
<p>Text i dont know</p>
</td>
<td>
<p>Text i dont know</p>
<p>Text i know</p>
<p>Text i dont know</p>
</td>
</table>
That means the lookahead also has to exclude any opening tag with a class
attribute. It now grows into this:
(?!</?\1\b|<\w+[^>]*\sclass="[^"]*"[^>]*>)
And finally, the element's content should include your target text (Text i know
). After the lookahead succeeds, we try to match that; if we succeed, the empty capturing group following it captures an empty string. Otherwise the dot consumes the next character and the process repeats.
When it's all done matching and the closing tag has been matched, the backreference \2
confirms that the target text was seen. Since that group didn't consume any characters, the backreference doesn't either, but it still reports success if the group participated in the match.
Back-assertions (as I like to call them) don't work in all flavors, and aren't officially supported in any of them, but they work in most of the Perl-derived flavors, including Python. (The most notable exceptions are JavaScript and other ECMAScript implementations.)
If you're reaction to this answer is abject horror, don't worry, I'm not offended. ;) Inspiring you to search harder for a solution that doesn't involve regexes is a successful outcome, too. (But it does work!)