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

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

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


当前回答

使用Html.fromHtml

HTML标签是

<a href=”…”> <b>,  <big>, <blockquote>, <br>, <cite>, <dfn>
<div align=”…”>,  <em>, <font size=”…” color=”…” face=”…”>
<h1>,  <h2>, <h3>, <h4>,  <h5>, <h6>
<i>, <p>, <small>
<strike>,  <strong>, <sub>, <sup>, <tt>, <u>

根据Android的官方文档,HTML中的任何标签都将显示为一个通用的替换字符串,你的程序可以通过并替换为真正的字符串。

超文本标记语言formHtml方法接受一个Html。TagHandler和Html。ImageGetter作为参数以及要解析的文本。

例子

String Str_Html=" <p>This is about me text that the user can put into their profile</p> ";

Then

Your_TextView_Obj.setText(Html.fromHtml(Str_Html).toString());

输出

这是关于我的文本,用户可以放入他们的个人资料

其他回答

〇应该可以

使用这个

  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.
classeString.replaceAll("\\<(/?[^\\>]+)\\>", "\\ ").replaceAll("\\s+", " ").trim() 

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

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

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

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

或者,可以使用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();