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

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

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


当前回答

您可能希望在剥离HTML之前将<br/>和</p>标记替换为换行符,以防止它像Tim建议的那样变得难以识别。

我能想到的唯一方法是删除HTML标记,但在尖括号之间留下非HTML标记,将检查HTML标记列表。沿着这条线……

replaceAll("\\<[\s]*tag[^>]*>","")

然后html解码特殊字符,如&结果不应该被认为是消毒的。

其他回答

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

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

我知道这是旧的,但我只是在一个项目,需要我过滤HTML,这工作得很好:

noHTMLString.replaceAll("\\&.*?\\;", "");

而不是这样:

html = html.replaceAll("&nbsp;","");
html = html.replaceAll("&amp;"."");

从字符串中删除HTML标签。在某个地方,我们需要解析一些字符串,这些字符串是由服务器端的Httpresponse等响应接收到的。

所以我们需要解析它。

在这里,我将展示如何从字符串中删除html标签。

    // sample text with tags

    string str = "<html><head>sdfkashf sdf</head><body>sdfasdf</body></html>";



    // regex which match tags

    System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("<[^>]*>");



    // replace all matches with empty strin

    str = rx.Replace(str, "");



    //now str contains string without html tags

使用HTML解析器而不是正则表达式。这对于Jsoup来说非常简单。

public static String html2text(String html) {
    return Jsoup.parse(html).text();
}

Jsoup还支持根据可定制的白名单删除HTML标记,如果您只想允许<b>, <i>和<u>,这是非常有用的。

参见:

RegEx匹配打开标记,但XHTML自包含标记除外 主要的Java HTML解析器的优缺点是什么? JSP/Servlet web应用中的跨站防护

〇应该可以

使用这个

  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.