首页 > 编程语言 > 详细

JAVA通过正则匹配html里面body标签的内容,去掉body标签

时间:2021-04-29 10:14:24      阅读:39      评论:0      收藏:0      [点我收藏+]

 

 

 /**
     *  获取html中body的内容 包含body标签
     * @param htmlStr  html代码
     * @return
     */
    public static String getBody(String htmlStr){


        String pattern = "<body[^>]*>([\\s\\S]*)<\\/body>";

        Pattern p_body = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        Matcher m_body = p_body.matcher(htmlStr);
        if (m_body.find()){
            return m_body.group();
        }
        return htmlStr;
    }


    /**
     * 取到html中body里面的内容 不包含body标签
     * @param htmlStr
     * @return
     */
    public static String removeBody(String htmlStr){

        /**
         * 获取html代码中body标签里的内容
         */
        htmlStr=getBody(htmlStr);

        //body开头标签
        String bodyEx_start = "<body[^>]*>";

        //body结尾标签
        String bodyEx_end = "<\\/body>";

        Pattern p_script = Pattern.compile(bodyEx_start, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // 过滤script标签

        Pattern p_style = Pattern.compile(bodyEx_end, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // 过滤style标签



        return htmlStr;
    }

 

 

 

 

如果要取得html代码中body里面的内容 不包含body标签

直接调用 removeBody


 

JAVA通过正则匹配html里面body标签的内容,去掉body标签

原文:https://www.cnblogs.com/pxblog/p/14716297.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!