views:

69

answers:

3

Basically I have an HTML fragment with <br> and <p></p> inside. I was able to remove all the HTML tags but doing so leaves the text in a bad format.

I want something like nl2br() in PHP except reverse the input and output and also takes into account <p> tags. is there a library for it in Java?

+2  A: 

You basically need to replace each <br> with \n and each <p> with \n\n. So, at the points where you succeed to remove them, you need to insert the \n and \n\n respectively.

Here's a kickoff example with help of the Jsoup HTML parser (the HTML example is intentionally written that way so that it's hard if not nearly impossible to use regex for this).

public static void main(String[] args) throws Exception {
    String text = br2nl("<p>p1l1<br/><!--</p>-->p1l2<br><!--<p>--></br><p id=p>p2l1<br class=b>p2l2</p>");
    System.out.println(text);
    System.out.println("-------------");
    String html = nl2br(text);
    System.out.println(html);
}

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().replaceAll("\\\\n", "\n");
}

public static String nl2br(String text) {
    return text.replaceAll("\n\n", "<p>").replaceAll("\n", "<br>");
}

Output:

p1l1
p1l2


p2l1
p2l2
-------------
<p>p1l1<br>p1l2<br> <p>p2l1<br>p2l2

A bit hacky, but it works. Jonathan Hedley, the guy behind Jsoup, has however planned a Formatter which should make this stuff easier.

BalusC
thanks. this works for me :D
You're welcome.
BalusC
+1  A: 

You should be able to use replaceAll. See http://www.rgagnon.com/javadetails/java-0454.html for an example. Just 2 of those, one for p and one for br. The example is going the other way, but you can change it around to replace the html with slash n

Joelio
+1  A: 

br2nl and p2nl are not too complicated. Give this a try:

String plain = htmlText.replaceAll("<br>","\\n").replaceAll("<p>","\\n\\n").replaceAll("</p>","");
Andreas_D
Well.. There are `<br/>`, `<br></br>`, `<br class="xxx">`, etc.. etc..
BalusC
@BalusC ... yes, an in 'reality' one would use an html parser and add the line.separators while extracting the text to a StringBuilder ;) I had the feeling, the OP used a kind of shortcut ;)
Andreas_D