是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式
replaceAll("\\<.*?>", "")
会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非html将被删除(即。*?在正则表达式中将消失)。
是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式
replaceAll("\\<.*?>", "")
会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非html将被删除(即。*?在正则表达式中将消失)。
当前回答
简单地执行JSoup .parse(html).text()有两个潜在的问题(对于JSoup 1.7.3):
它从文本中删除换行符 它转换文本<脚本>>到<脚本
如果您使用它来防止XSS,这有点烦人。下面是我在一个改进的解决方案中最好的尝试,使用JSoup和Apache StringEscapeUtils:
// breaks multi-level of escaping, preventing &lt;script&gt; to be rendered as <script>
String replace = input.replace("&", "");
// decode any encoded html, preventing <script> 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\"/>", ""},
{"<script>", ""},
{"&lt;script&gt;", "lt;scriptgt;"}, // best effort
{"\" ' > < \n \\ é å à ü and & preserved", "\" ' > < \n \\ é å à ü and & preserved"}
如果你有办法让它变得更好,请告诉我。
其他回答
我知道这是旧的,但我只是在一个项目,需要我过滤HTML,这工作得很好:
noHTMLString.replaceAll("\\&.*?\\;", "");
而不是这样:
html = html.replaceAll(" ","");
html = html.replaceAll("&"."");
classeString.replaceAll("\\<(/?[^\\>]+)\\>", "\\ ").replaceAll("\\s+", " ").trim()
使用Jericho也非常简单,并且可以保留一些格式(例如换行符和链接)。
Source htmlSource = new Source(htmlText);
Segment htmlSeg = new Segment(htmlSource, 0, htmlSource.length());
Renderer htmlRend = new Renderer(htmlSeg);
System.out.println(htmlRend.toString());
使用JSoup保留新行信息的一种方法是在所有新行标记之前使用一些虚拟字符串,执行JSoup并将虚拟字符串替换为“\n”。
String html = "<p>Line one</p><p>Line two</p>Line three<br/>etc.";
String NEW_LINE_MARK = "NEWLINESTART1234567890NEWLINEEND";
for (String tag: new String[]{"</p>","<br/>","</h1>","</h2>","</h3>","</h4>","</h5>","</h6>","</li>"}) {
html = html.replace(tag, NEW_LINE_MARK+tag);
}
String text = Jsoup.parse(html).text();
text = text.replace(NEW_LINE_MARK + " ", "\n\n");
text = text.replace(NEW_LINE_MARK, "\n\n");
您可能希望在剥离HTML之前将<br/>和</p>标记替换为换行符,以防止它像Tim建议的那样变得难以识别。
我能想到的唯一方法是删除HTML标记,但在尖括号之间留下非HTML标记,将检查HTML标记列表。沿着这条线……
replaceAll("\\<[\s]*tag[^>]*>","")
然后html解码特殊字符,如&结果不应该被认为是消毒的。