简体   繁体   English

Java替换String中的所有非HTML标记

[英]Java replace all non-HTML Tags in a String

I'd like to replace all the tag-looking parts in a String if those are not valid HTML tags. 如果这些部分不是有效的HTML标记,我想替换String中所有看起来像标记的部分。 A tag-looking part is something enclosed in <> brackets. 带标签的部分是用<>括号括起来的东西。 Eg. 例如。 <myemail@email.com> or <hello> but <br> , <div> , and so on has to be kept. <myemail@email.com><hello>但必须保留<br><div>等。

Do you have any idea how to achieve this? 你知道如何实现这个目标吗?

Any help is appreciated! 任何帮助表示赞赏!

cheers, 干杯,

balázs 巴拉兹

You can use JSoup to clean HTML. 您可以使用JSoup来清理HTML。

String cleaned = Jsoup.clean(html, Whitelist.relaxed());

You can either use one of the defined Whitelists or you can create your own custom one in which you specify which HTML elements you wish to allow through the cleaner. 您可以使用其中一个已定义的白名单 ,也可以创建自己的自定义白名单 ,在其中指定希望通过清理器允许的HTML元素。 Everything else is removed. 其他一切都被删除了。


Your specific example would be: 您的具体示例是:

String html = "one two three <blabla> four <text> five <div class=\"bold\">six</div>";
String cleaned = Jsoup.clean(html, Whitelist.relaxed().addAttributes("div", "class"));
System.out.println(cleaned);

Output: 输出:

one two three  four  five 
<div class="bold">
 six
</div>

看一下java.util.Scanner类 - 你可以设置一个分隔符,然后查看字符串是否与HTML标记匹配 - 你必须构建一个应该被忽略的字符串数组。

You may also want to include ending tags in your comparison algorithm. 您可能还希望在比较算法中包含结束标记。 So you may want to look for a forward slash(html end tag) and strip it before your comparison. 因此,您可能需要查找正斜杠(html结束标记)并在比较之前将其删除。

If you do it in order to display untrusted data on the web page, simple removing of invalid tags is not enough. 如果您这样做是为了在网页上显示不受信任的数据,那么简单地删除无效标记是不够的。 Take a look at OWASP AntiSamy . 看看OWASP AntiSamy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM