過濾HTML以及CSS樣式等標籤
阿新 • • 發佈:2019-02-02
現在在頁面上要取出文章內容的一部分作為描述,比如下圖所示:
紅線框裡的資料是該篇文章的內容的一部分,但是文章內容儲存的時候會有html程式碼等的格式
為了顯示正常需要過濾html標籤,程式碼如下:
程式中只需呼叫:public String delHTMLTag(String htmlStr){ String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定義style的正則表示式 String regEx_html="<[^>]+>"; //定義HTML標籤的正則表示式 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標籤 htmlStr=htmlStr.replace(" ",""); htmlStr=htmlStr.replaceAll("\\s*|\t|\r|\n",""); htmlStr=htmlStr.replace("“",""); htmlStr=htmlStr.replace("”",""); htmlStr=htmlStr.replaceAll(" ",""); return htmlStr.trim(); //返回文字字串 }
String content = delHTMLTag(content);