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

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

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


当前回答

你可以简单地用多个replaceAll()方法像

String RemoveTag(String html){
   html = html.replaceAll("\\<.*?>","")
   html = html.replaceAll("&nbsp;","");
   html = html.replaceAll("&amp;"."");
   ----------
   ----------
   return html;
}

使用这个链接,你需要的最常见的替换: http://tunes.org/wiki/html_20special_20characters_20and_20symbols.html

这很简单,但很有效。我使用这个方法首先删除垃圾,但不是第一行,即replaceAll(“\<.*?>”,“”),然后我使用特定的关键字搜索索引,然后使用.substring(开始,结束)方法去除不必要的东西。因为这更健壮,你可以在整个html页面中准确地指出你需要什么。

其他回答

我认为过滤html标签最简单的方法是:

private static final Pattern REMOVE_TAGS = Pattern.compile("<.+?>");

public static String removeTags(String string) {
    if (string == null || string.length() == 0) {
        return string;
    }

    Matcher m = REMOVE_TAGS.matcher(string);
    return m.replaceAll("");
}

使用Jericho也非常简单,并且可以保留一些格式(例如换行符和链接)。

    Source htmlSource = new Source(htmlText);
    Segment htmlSeg = new Segment(htmlSource, 0, htmlSource.length());
    Renderer htmlRend = new Renderer(htmlSeg);
    System.out.println(htmlRend.toString());

你可以简单地使用Android默认的HTML过滤器

    public String htmlToStringFilter(String textToFilter){

    return Html.fromHtml(textToFilter).toString();

    }

上面的方法将为您的输入返回经过HTML过滤的字符串。

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

public static String stripHtmlTags(String html) {

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

}

你可以简单地用多个replaceAll()方法像

String RemoveTag(String html){
   html = html.replaceAll("\\<.*?>","")
   html = html.replaceAll("&nbsp;","");
   html = html.replaceAll("&amp;"."");
   ----------
   ----------
   return html;
}

使用这个链接,你需要的最常见的替换: http://tunes.org/wiki/html_20special_20characters_20and_20symbols.html

这很简单,但很有效。我使用这个方法首先删除垃圾,但不是第一行,即replaceAll(“\<.*?>”,“”),然后我使用特定的关键字搜索索引,然后使用.substring(开始,结束)方法去除不必要的东西。因为这更健壮,你可以在整个html页面中准确地指出你需要什么。