What would be an optimal way, using Jsoup, to extract all HTML (either to a String, Document or Elements) between two blocks that conform to this pattern:
<strong>
{any HTML could appear here, except for a <strong> pair}
</strong>
...
{This is the HTML I need to extract.
any HTML could appear here, except for a <strong> pair}
...
<strong>
{any HTML could appear here, except for a <strong> pair}
</strong>
Using a regex this could be simple, if I apply it on the entire body.html():
(<strong>.+</strong>)(.+)(<strong>.+</strong>)
^
+----- There I have my HTML content
But as I learned from a similar challenge, performance could be improved (even if the code is slightly longer) if I use an already Jsoup-parsed DOM -- except that this time neither Element.nextSibling()
nor Element.nextElementSibling()
can come to the rescue.
I searched for something like jQuery's nextUntil in Jsoup, for example, but couldn't really find something similar.
Is it possible to come up with something better than the above regex-based approach?
I don't know if it's faster but maybe something like this will work:
Elements strongs = doc.select("strong");
Element f = strongs.first();
Element l = strongs.last();
Elements siblings = f.siblingElements();
List<Element> result = siblings.subList(siblings.firstIndexOf(f) + 1,siblings.lastIndexOf(l));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With