是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式
replaceAll("\\<.*?>", "")
会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非html将被删除(即。*?在正则表达式中将消失)。
是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式
replaceAll("\\<.*?>", "")
会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非html将被删除(即。*?在正则表达式中将消失)。
当前回答
我知道这个问题已经有一段时间没有被问到了,但我找到了另一个解决方案,这对我来说很有效:
Pattern REMOVE_TAGS = Pattern.compile("<.+?>");
Source source= new Source(htmlAsString);
Matcher m = REMOVE_TAGS.matcher(sourceStep.getTextExtractor().toString());
String clearedHtml= m.replaceAll("");
其他回答
classeString.replaceAll("\\<(/?[^\\>]+)\\>", "\\ ").replaceAll("\\s+", " ").trim()
在Android上试试这个:
String result = Html.fromHtml(html).toString();
值得注意的是,如果您试图在Service Stack项目中完成此操作,那么它已经是一个内置的字符串扩展
using ServiceStack.Text;
// ...
"The <b>quick</b> brown <p> fox </p> jumps over the lazy dog".StripHtml();
你可以使用这个方法从字符串中删除HTML标签,
public static String stripHtmlTags(String html) {
return html.replaceAll("<.*?>", "");
}
你可以简单地用多个replaceAll()方法像
String RemoveTag(String html){
html = html.replaceAll("\\<.*?>","")
html = html.replaceAll(" ","");
html = html.replaceAll("&"."");
----------
----------
return html;
}
使用这个链接,你需要的最常见的替换: http://tunes.org/wiki/html_20special_20characters_20and_20symbols.html
这很简单,但很有效。我使用这个方法首先删除垃圾,但不是第一行,即replaceAll(“\<.*?>”,“”),然后我使用特定的关键字搜索索引,然后使用.substring(开始,结束)方法去除不必要的东西。因为这更健壮,你可以在整个html页面中准确地指出你需要什么。