从字符串中删除 HTML 标签 [英] Remove HTML tags from a String
本文介绍了从字符串中删除 HTML 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有什么好方法可以从 Java 字符串中删除 HTML?一个简单的正则表达式,如
Is there a good way to remove HTML from a Java string? A simple regex like
replaceAll("\\<.*?>", "")
会工作,但像 &
这样的东西不会被正确转换,两个尖括号之间的非 HTML 将被删除(即 .*?
中的正则表达式将消失).
will work, but things like &
wont be converted correctly and non-HTML between the two angle brackets will be removed (i.e. the .*?
in the regex will disappear).
推荐答案
使用 HTML 解析器而不是正则表达式.这对于 Jsoup 来说非常简单.
Use a HTML parser instead of regex. This is dead simple with Jsoup.
public static String html2text(String html) {
return Jsoup.parse(html).text();
}
Jsoup 还支持针对可自定义的白名单删除 HTML 标签,这非常如果您只想允许例如、
和
.
Jsoup also supports removing HTML tags against a customizable whitelist, which is very useful if you want to allow only e.g. <b>
, <i>
and <u>
.
这篇关于从字符串中删除 HTML 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文