CommentArea implements ContentManipulator { @Override public void manipulate(Document document) { document .select("p:contains(" + COMMENT_END + ")") .forEach( last -> { if (last.ownText().contains(COMMENT_START)) { last.wrap(ASIDE); } else { int index = last.elementSiblingIndex(); Elements allSiblings = last.siblingElements(); Elements pSiblings = allSiblings.select("p"); Element startSibling = null; for (int i = index - 1; i >= 0; i--) { Element e = pSiblings.get(i); if (e.ownText().contains(COMMENT_START)) { startSibling = e; break; } } if (startSibling != null) { for (int i = startSibling.elementSiblingIndex(); i < index; i++) { allSiblings.get(i).wrap(ASIDE); } last.wrap(ASIDE); } } }); }  @Override void manipulate(Document document);  }
@Test public void testSingle() { Document document = Jsoup.parseBodyFragment( "<p><b>THIS IS A SUBJECT HEADING</b></p><p>COMMENT: This is a comment. COMMENT ENDS</p><p>This is more text</p><p>COMMENT: This is a another comment. COMMENT ENDS</p>"); manipulator.manipulate(document); Elements asides = document.select("aside"); assertEquals(2, asides.size()); assertEquals("COMMENT: This is a comment. COMMENT ENDS", asides.first().text()); assertEquals("COMMENT: This is a another comment. COMMENT ENDS", asides.last().text()); }
@Test public void testMultiParagraph() { Document document = Jsoup.parseBodyFragment( "<p>Not a comment</p><p>COMMENT: Line one</p><p>Line two COMMENT ENDS</p>"); manipulator.manipulate(document); Elements asides = document.select("aside"); assertEquals(2, asides.size()); assertEquals("COMMENT: Line one", asides.first().text()); assertEquals("Line two COMMENT ENDS", asides.last().text()); }