java正則表達式去掉所有HTML標籤

  1. package com.xz.cxzy.utils;  
  2.   
  3. import java.util.regex.Matcher;  
  4. import java.util.regex.Pattern;  
  5.   
  6. public class HtmlUtil {  
  7.     private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"// 定義script的正則表達式  
  8.     private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"// 定義style的正則表達式  
  9.     private static final String regEx_html = "<[^>]+>"// 定義HTML標籤的正則表達式  
  10.     private static final String regEx_space = "\\s*|\t|\r|\n";//定義空格回車換行符  
  11.       
  12.     /** 
  13.      * @param htmlStr 
  14.      * @return 
  15.      *  刪除Html標籤 
  16.      */  
  17.     public static String delHTMLTag(String htmlStr) {  
  18.         Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);  
  19.         Matcher m_script = p_script.matcher(htmlStr);  
  20.         htmlStr = m_script.replaceAll(""); // 過濾script標籤  
  21.   
  22.         Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);  
  23.         Matcher m_style = p_style.matcher(htmlStr);  
  24.         htmlStr = m_style.replaceAll(""); // 過濾style標籤  
  25.   
  26.         Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);  
  27.         Matcher m_html = p_html.matcher(htmlStr);  
  28.         htmlStr = m_html.replaceAll(""); // 過濾html標籤  
  29.   
  30.         Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);  
  31.         Matcher m_space = p_space.matcher(htmlStr);  
  32.         htmlStr = m_space.replaceAll(""); // 過濾空格回車標籤  
  33.         return htmlStr.trim(); // 返回文本字符串  
  34.     }  
  35.       
  36.     public static String getTextFromHtml(String htmlStr){  
  37.         htmlStr = delHTMLTag(htmlStr);  
  38.         htmlStr = htmlStr.replaceAll(" """);  
  39.         htmlStr = htmlStr.substring(0, htmlStr.indexOf("。")+1);  
  40.         return htmlStr;  
  41.     }  
  42.       
  43.     public static void main(String[] args) {  
  44.         String str = "<div style='text-align:center;'> 整治“四風”   清弊除垢<br/><span style='font-size:14px;'> </span><span style='font-size:18px;'>公司召開黨的羣衆路線教育實踐活動動員大會</span><br/></div>";  
  45.         System.out.println(getTextFromHtml(str));  
  46.     }  
  47. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章