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

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

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


当前回答

在Android上试试这个:

String result = Html.fromHtml(html).toString();

其他回答

HTML转义真的很难做对-我绝对建议使用库代码来做这件事,因为它比你想象的要微妙得多。在Apache的StringEscapeUtils中有一个非常好的库,可以在Java中处理这个问题。

从字符串中删除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标签| HTML实体|空白的HTML内容)的另一个变体

content.replaceAll ("(<.*?>)|(&.*?;)|([ ]{ 2 ,})", "");其中content是一个字符串。

听起来好像您想从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;
}

简单地执行JSoup .parse(html).text()有两个潜在的问题(对于JSoup 1.7.3):

它从文本中删除换行符 它转换文本&lt;脚本&gt;>到<脚本

如果您使用它来防止XSS,这有点烦人。下面是我在一个改进的解决方案中最好的尝试,使用JSoup和Apache StringEscapeUtils:

// breaks multi-level of escaping, preventing &amp;lt;script&amp;gt; to be rendered as <script>
String replace = input.replace("&amp;", "");
// decode any encoded html, preventing &lt;script&gt; to be rendered as <script>
String html = StringEscapeUtils.unescapeHtml(replace);
// remove all html tags, but maintain line breaks
String clean = Jsoup.clean(html, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));
// decode html again to convert character entities back into text
return StringEscapeUtils.unescapeHtml(clean);

注意,最后一步是因为我需要将输出作为纯文本使用。如果您只需要HTML输出,那么您应该能够删除它。

下面是一堆测试用例(从输入到输出):

{"regular string", "regular string"},
{"<a href=\"link\">A link</a>", "A link"},
{"<script src=\"http://evil.url.com\"/>", ""},
{"&lt;script&gt;", ""},
{"&amp;lt;script&amp;gt;", "lt;scriptgt;"}, // best effort
{"\" ' > < \n \\ é å à ü and & preserved", "\" ' > < \n \\ é å à ü and & preserved"}

如果你有办法让它变得更好,请告诉我。