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

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

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


当前回答

如果你是为Android编写程序,你可以这样做……

androidx.core.text.HtmlCompat.fromHtml(指令,HtmlCompat.FROM_HTML_MODE_LEGACY) .toString ()

其他回答

听起来好像您想从HTML转换为纯文本。 如果是这样的话,请查看www.htmlparser.org。下面是一个示例,它从URL中找到的html文件中剥离所有标记。 它使用org.htmlparser.beans.StringBean。

static public String getUrlContentsAsText(String url) {
    String content = "";
    StringBean stringBean = new StringBean();
    stringBean.setURL(url);
    content = stringBean.getStrings();
    return content;
}

〇应该可以

使用这个

  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.

或者,可以使用HtmlCleaner:

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

值得注意的是,如果您试图在Service Stack项目中完成此操作,那么它已经是一个内置的字符串扩展

using ServiceStack.Text;
// ...
"The <b>quick</b> brown <p> fox </p> jumps over the lazy dog".StripHtml();

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

public static String stripHtmlTags(String html) {

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

}