JAVA字符串去掉html代码,获取内容

 

有时候我们需要在html代码中获取到文本内容,需要把html代码中的标签过滤掉

 

String htmlStr="html代码";
htmlStr = htmlStr.replaceAll("<[.[^<]]*>", "");

 

 

 

另外一种方式

// 标题去掉样式 空格 问hao
    private static Pattern FilePattern = Pattern.compile("[\\\\/:*?\"<>|]");

    public static String filenameFilter(String htmlStr) {
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
        String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

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

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

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // 过滤html标签

        String str = htmlStr.trim(); // 返回文本字符串
        str = str == null ? null : FilePattern.matcher(str).replaceAll("");
        str = str.replaceAll("\\s*", "").replaceAll("", "");
        return str;
    }

 

posted @ 2020-10-16 09:12  yvioo  阅读(2304)  评论(0编辑  收藏  举报