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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM