是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式
replaceAll("\\<.*?>", "")
会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非html将被删除(即。*?在正则表达式中将消失)。
是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式
replaceAll("\\<.*?>", "")
会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非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("");
}
其他回答
您可能希望在剥离HTML之前将<br/>和</p>标记替换为换行符,以防止它像Tim建议的那样变得难以识别。
我能想到的唯一方法是删除HTML标记,但在尖括号之间留下非HTML标记,将检查HTML标记列表。沿着这条线……
replaceAll("\\<[\s]*tag[^>]*>","")
然后html解码特殊字符,如&结果不应该被认为是消毒的。
有时html字符串来自xml,带有这样的<。在使用Jsoup时,我们需要解析它,然后清理它。
Document doc = Jsoup.parse(htmlstrl);
Whitelist wl = Whitelist.none();
String plain = Jsoup.clean(doc.text(), wl);
而仅使用Jsoup.parse(htmlstrl).text()不能删除标签。
或者,可以使用HtmlCleaner:
private CharSequence removeHtmlFrom(String html) {
return new HtmlCleaner().clean(html).getText();
}
从字符串中删除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.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());
输出
这是关于我的文本,用户可以放入他们的个人资料