i have some text which I know and I need to find first tag with class defined around that text.
Example:
<table>
<td class="foo">
<p>...</p>
</td>
<td class="bar">
<p>Text i dont know</p>
<p>Text i know</p>
<p>Text i dont know</p>
</td>
</table>
I tried a lot of things. I know how to find a closing tag, but when I try to find opening tag, my regex returns td with class “foo” instead one with class “bar”.
I will really appreciate your help.
Edit:
I want to do it in python. I provided weak specification of the problem. That tag dont have to be tag, it can be any tag with class specified. I dont want to “parse” html with regex, but i dont see any other way how to do such thing without using regular expressions.
What i need is to find first tag around that tag which have class specified.
Okay, here we go!
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):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 aclassattribute is required too, so the first part becomes:The question wasn’t prefectly clear on this, but I’m assuming you want to match the most immediate enclosing element with a
classattribute. That is, in the following text, you want to match thetd.yes-meelement, not thetableelement.That means the lookahead also has to exclude any opening tag with a
classattribute. It now grows into this: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
\2confirms 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!)