Ignore strings with balanced "<>"

I’m not an expert with Lua patterns and when I want to do some pattern matching, I usually go by with trial and error.
However, I finally met a match I couldn’t match (no pun intended :upside_down_face:)

Lets say I have a html string like this stored in a variable:
local html = "<a class='dog' href="https://www.example.com/lost_dog.png">I am looking for my dog</a>"

Now, I want to replace the “dog” that is NOT enclosed with < and > with “cat”.

Is such even possible with Lua?

I would probably approach this by creating a function that looks for all pairs of < and >, then try to find your chosen word that isn’t inside the tags. You should be able to use string.find() for that.

Done this before (not in lua). You search char by char until you find a > now start building a string until you find a <. Now you have the chars between > and <. Now a replace of dog for cat is a simple procedure.

It sounds like you want %bxy, or rather %b<>. See here under “Pattern Item”.

Thank you all. I am building an RSS feed reader that displays its results on a native.newWebview and it allows the user to search through news feeds.

Unfortunately, some feeds have CDATA elements that also have HTML tags so – referring to my example – I try to capture all matches of dog and surround them with tags like <span class='search-match'>dog</span> (and then use a CSS stylesheet to highlight the result), I will end up inserting a <span> tag into the <a> tags class and cause chaos throughout the entire HTML.

I decided to forgo it. A lot of memory is already put into doing case-insensitive matching and most of these feeds are hundreds of lines long and doing another string.gsub operation to highlight matches will slow down the app considerably (and bore potential users). I will keep trying to find a quick easy way that doesn’t require a lot of nested functions.
But I do thank you all for your answers.