有時候我們需要在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; }