现在的位置: 首页 > 综合 > 正文

Java过滤HTML标签

2013年09月19日 ⁄ 综合 ⁄ 共 1198字 ⁄ 字号 评论关闭
  public static String delHTMLTag( String htmlStr )
    {
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
        String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
        String regEx_blank = "\\s*|\t|\r|\n"; // 定义空格,回车,换行符等的标签的正则表达式
        String regEx_nbsp = " ";


        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标签

        System.out.println("before  :");
        System.out.println(htmlStr);
        Pattern p_nbsp = Pattern.compile( regEx_nbsp, Pattern.CASE_INSENSITIVE );
        Matcher m_nbsp = p_nbsp.matcher( htmlStr );
        htmlStr = m_nbsp.replaceAll(""); // 过滤空格标签
        System.out.println("after  :");
        System.out.println(htmlStr);

        Pattern p_blank = Pattern.compile( regEx_nbsp, Pattern.CASE_INSENSITIVE );
        Matcher m_blank = p_blank.matcher( htmlStr );
        htmlStr = m_blank.replaceAll(""); // 过滤空格标签

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

抱歉!评论已关闭.