You basically need to replace each <br>with \nand each <p>with \n\n. So, in those places where you manage to remove them, you need to insert \nand \n\naccordingly.
Jsoup HTML- ( HTML , , ).
public static void main(String[] args) throws Exception {
String originalHtml = "<p>p1l1<br/><!--</p>-->p1l2<br><!--<p>--></br><p id=p>p2l1<br class=b>p2l2</p>";
String text = br2nl(originalHtml);
String newHtml = nl2br(text);
System.out.println("-------------");
System.out.println(text);
System.out.println("-------------");
System.out.println(newHtml);
}
public static String br2nl(String html) {
Document document = Jsoup.parse(html);
document.select("br").append("\\n");
document.select("p").prepend("\\n\\n");
return document.text().replace("\\n", "\n");
}
public static String nl2br(String text) {
return text.replace("\n\n", "<p>").replace("\n", "<br>");
}
(: replaceAll() , charsequence-by-charsequence , regexpattern-by-charsequence)
:
<p>p1l1<br/>p1l2<br></br><p id=p>p2l1<br class=b>p2l2</p>
-------------
p1l1
p1l2
p2l1
p2l2
-------------
<p>p1l1 <br>p1l2 <br> <br> <p>p2l1 <br>p2l2
, .