去除資料中帶有HTML標籤和樣式
阿新 • • 發佈:2019-02-16
- 有些資料如果只是帶有標籤,還好處理直接用函式替換就可以了。不過裡面還包含樣式,就麻煩點就要正則表示式了
/**
* 清除Html標籤
*
* @param inputString 目標字串
* @return 處理後的結果
*/
public static String removeHtmlTag(String inputString) {
if (inputString == null)
return null;
String htmlStr = inputString; / / 含html標籤的字串
String textStr = "";
Pattern p_script;
Matcher m_script;
Pattern p_style;
Matcher m_style;
Pattern p_html;
Matcher m_html;
Pattern p_special;
Matcher m_special;
try {
//定義script的正則表示式{或<script[^>]*?>[\\s\\S]*?<\\/script >
String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
//定義style的正則表示式{或<style[^>]*?>[\\s\\S]*?<\\/style>
String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>" ;
// 定義HTML標籤的正則表示式
String regEx_html = "<[^>]+>";
// 定義一些特殊字元的正則表示式 如:
String regEx_special = "\\&[a-zA-Z]{1,10};";
p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 過濾script標籤
p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 過濾style標籤
p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 過濾html標籤
p_special = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE);
m_special = p_special.matcher(htmlStr);
htmlStr = m_special.replaceAll(""); // 過濾特殊標籤
textStr = htmlStr;
} catch (Exception e) {
e.printStackTrace();
}
return textStr;// 返回文字字串
}