public static String delHtmlTag(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标签
return htmlStr.trim(); // 返回文本字符串
}
你可能也看出来了,当HTML的一个内容中包含成对的大于小于符号时,也就构成了“<>”,那么其中的内容会被当成HTML标签属性内容而删掉。所以说不够严谨。HTML标签的转义、反转义
java中可以借助第三方的工具方便的完成,apache.commons.lang包包含了很多常用的工具,这其中有一个非常好用的字符串转义工具:StringEscapeUtils.利用它可以方便的对字符进行转义与反转义,而且是细化到不同语言对象,常见的Java、Html、JavaScript等代码它都能搞定非常好用。
随便看一下其方法,很强大有木有:

简单写个demo测试一下:
String str = "<h1 style='width:100px; height:100px'>hello</h1>";
System.out.println("测试字符串:" + str);
String str1 = StringEscapeUtils.escapeHtml4(str);
System.out.println("转义:" + str1);
String str2 = StringEscapeUtils.unescapeHtml4(str1);
System.out.println("反转义:" + str2);
输出:
测试字符串:<h1 style='width:100px; height:100px'>hello</h1>
转义:<h1 style='width:100px; height:100px'>hello</h1>
反转义:<h1 style='width:100px; height:100px'>hello</h1>
一切正常。注意:从Commons版本3.6开始,StringEscapeUtils被转移到了org.apache.commons.text包下,所以继续用commons.lang下的StringEscapeUtils会显示已过时。建议使用commons.text包下的StringEscapeUtils。
前端的相关操作
有时候以上操作可能发生在前端,这里我也收集了相关的JavaScript方法:
//删除HTML标签(与Java同样的正则表达式,所以依旧不太严谨)
function delHtmlTag(str) {
return str.replace(/<[^>]+>/g, "");
}
//HTML标签转义
function html2Escape(sHtml) {
return sHtml.replace(/[<>&"]/g, function (c) {
return {'<': '<', '>': '>', '&': '&', '"': '"'}[c];
});
}
//HTML标签反转义
function escape2Html(str) {
var arrEntities = {'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"'};
return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
return arrEntities[t];
});
}