Java去除完全闭合html标签、去除部分未闭合的html标签的几种方式

1. 使用正则表达式去除html标签

    /**
     * 去除Html标签
     * 
     * @param html
     *            html内容
     * @return 去除标签后的文本
     */
    public static String dislodgeHtmlLabel(String html) {

        if (Objects.isNull(html)) {
            return "";
        }

        // 过滤script标签
        Pattern pscript = Pattern.compile("<script[^>]*?>[\\s\\S]*?<\\/script>", Pattern.CASE_INSENSITIVE);

        // 过滤style的正则
        Pattern pstyle = Pattern.compile("<style[^>]*?>[\\s\\S]*?<\\/style>", Pattern.CASE_INSENSITIVE);

        // 过滤html标签的正则
        Pattern phtml = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);

        // 执行过滤script标签
        Matcher mscript = pscript.matcher(html);
        html = mscript.replaceAll("");

        // 执行过滤style标签
        Matcher mstyle = pstyle.matcher(html);
        html = mstyle.replaceAll("");

        // 执行过滤html标签
        Matcher mHtml = phtml.matcher(html);
        html = mHtml.replaceAll("");

        // 返回文本字符串
        return html.trim();
    }

2. 使用Jsoup组件去除html标签

pom文件:

      <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.12.1</version>
      </dependency>
  
    /**
     * 去除Html标签
     * 
     * @param html
     *            html内容
     * @return 去除标签后的文本
     */
    public static String wipeOffHtmlLabel(String html) {

        // null则返回空字符串
        if (Objects.isNull(html)) {
            return "";
        }

        // 异常返回自身
        try {
            return Jsoup.parse(html).text();
        } catch (Exception e) {
            return html;
        }
    }

3. 运行情况


    public static void main(String[] args) {

        // 未闭合的html标签
        String notClosed = "<p>你大爷的</p><p><a href=\"http://www.baidu.com\" rel=\"noopener noreferrer\" target=\"_blank\">百度</a><br><br><img alt=\"\" src=\"http://www.baidu.c";

        // 正常闭合html标签
        String normal = "<p><strong><span style=\"font-size: 18px;\">你是个傻小子</span></strong></p>";

        // 1. 使用正则表达式
        String notClosed1 = dislodgeHtmlLabel(notClosed);
        String normal1 = dislodgeHtmlLabel(normal);
        System.out.println(notClosed1);
        System.out.println(normal1);

        System.out.println("*****************************************");
        // 2. 使用Jsoup组件
        String notClosed2 = wipeOffHtmlLabel(notClosed);
        String normal2 = wipeOffHtmlLabel(normal);
        System.out.println(notClosed2);
        System.out.println(normal2);

    }

结果:
在这里插入图片描述

4. 结论

  1. 完全闭合的标签推荐使用正则表达式,因为是轻量级的。
  2. 如果是从数据库中查出截断的html文本,最好使用Jsoup组件,支持去除未闭合的标签。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值