【Java】去除富文本里的html和特殊标签
/**
* 去掉字符串中的 \t \r \n
* <p>
* param str
*
* @return
* @author Rex
*/
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n|");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
/**
* 删除Html标签
* <p>
* param inputString
*
* @return
* @author Rex
*/
public static String removeHtmlTag(String inputString) {
if (inputString == null)
return null;
String htmlStr = inputString; // 含html标签的字符串
String textStr = "";
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};";
textStr = getString(htmlStr, regEx_script, regEx_style, regEx_html, regEx_special);
} catch (Exception e) {
e.printStackTrace();
}
return textStr;// 返回文本字符串
}
private static String getString(String htmlStr, String... args) {
Pattern p_script;
Matcher m_script;
for (String regEx: args) {
p_script = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤
}
return htmlStr;
}