是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式

replaceAll("\\<.*?>", "") 

会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非html将被删除(即。*?在正则表达式中将消失)。


当前回答

或者,可以使用HtmlCleaner:

private CharSequence removeHtmlFrom(String html) {
    return new HtmlCleaner().clean(html).getText();
}

其他回答

你可以使用这个方法从字符串中删除HTML标签,

public static String stripHtmlTags(String html) {

    return html.replaceAll("<.*?>", "");

}

〇应该可以

使用这个

  text.replaceAll('<.*?>' , " ") -> This will replace all the html tags with a space.

  text.replaceAll('&.*?;' , "")-> this will replace all the tags which starts with "&" and ends with ";" like &nbsp;, &amp;, &gt; etc.

另一种方法是使用com.google.gdata.util.common.html.HtmlToText类 就像

MyWriter.toConsole(HtmlToText.htmlToPlainText(htmlResponse));

虽然这不是防弹代码,但当我在维基百科条目上运行它时,我也得到了风格信息。然而,我相信对于小/简单的工作,这将是有效的。

我经常发现我只需要去掉注释和脚本元素。这已经为我可靠地工作了15年,可以很容易地扩展到处理HTML或XML中的任何元素名称:

// delete all comments
response = response.replaceAll("<!--[^>]*-->", "");
// delete all script elements
response = response.replaceAll("<(script|SCRIPT)[^+]*?>[^>]*?<(/script|SCRIPT)>", "");

使用JSoup保留新行信息的一种方法是在所有新行标记之前使用一些虚拟字符串,执行JSoup并将虚拟字符串替换为“\n”。

String html = "<p>Line one</p><p>Line two</p>Line three<br/>etc.";
String NEW_LINE_MARK = "NEWLINESTART1234567890NEWLINEEND";
for (String tag: new String[]{"</p>","<br/>","</h1>","</h2>","</h3>","</h4>","</h5>","</h6>","</li>"}) {
    html = html.replace(tag, NEW_LINE_MARK+tag);
}

String text = Jsoup.parse(html).text();

text = text.replace(NEW_LINE_MARK + " ", "\n\n");
text = text.replace(NEW_LINE_MARK, "\n\n");