It's generally not advised to try and parse HTML with a regular expressions. There's a number of potential problems, but nested tags is one of the big ones. If that advice is applicable here depends on the possible values your code needs to accept.
Apex's ability to work with XML as a document model is solid, but searching that tree is something that you'd have to build support for sadly. This means you'd end up writing a lot of code, and in the end it would quite possibly perform worse (a guess, partially due to the reflection call overhead of the runtime). If you do have to go down the XML parsing route there's two main options:
Dom.Document and Dom.XMLNode. These let you navigate between XML nodes, descending to children, back up, or really anywhere. You're free to hop around the tree processing it, but that means recursion or similar to handle it - and apex has a relatively small stack depth.
XmlStreamReader has a loop-based approach of reading the document as it goes, which means no going back up to a parent. The upside is this is probably much less code, and conceptually simpler than traversing an XML node tree. I'll also speculate wildly that it's much more efficient on heap use.
Based on that I'd advise sanity checking if regex is the right tool for the job, hoping it is since it's clearly much simpler to use here. If it's not I'd take a good hard look at using XMLStreamReader to parse.
There are a few upsides to XML parsing though, particularly that it's quite robust compared to handling the document fragment as text. It should handle all sorts of variations, like <td />
, odd whitespace, attributes, and all the other goodies that XML supports.
>
character too?<td>
tags?