java-去除html中的标签或者元素属性(正则表达式/jsoup)


如一篇使用富文本编辑器编辑的新闻稿,需要在列表页面截取前200字作为摘要,此时需要去除html标签,截取真正的文本部分。

/**
* 删除Html标签
*/
public static String removeHtmlTag(String htmlStr) {
//定义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 = "<[^>]+>";
//定义一些特殊字符的正则表达式 如:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
String regEx_special = "\\&[a-zA-Z]{1,10};";

//1.过滤script标签
Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll("");
//2.过滤style标签
Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
Matcher m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll("");
//3.过滤html标签
Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll("");
//4.过滤特殊标签
Pattern p_special = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE);
Matcher m_special = p_special.matcher(htmlStr);
htmlStr = m_special.replaceAll("");

return htmlStr;
}


使用正则表达式去除html中的元素属性
业务场景:
如某网站历史数据中有很多富文本编辑器编辑的新闻稿,里面定义了很多行内样式,现开发了新网站,统一定义了样式,进行数据迁移时需要去除这些行内样式,但保留标签。
代码实现:
private static final String regEx_tag = "<(\\w[^>|\\s]*)[\\s\\S]*?>";

public static String removeEleProp(String htmlStr) {
Pattern p = Pattern.compile(regEx_tag, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(htmlStr);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String tagWithProp= m.group(0);
String tag =m.group(1);
if ("img".equals(tag)) {
//img标签保留属性,可进一步处理删除无用属性,仅保留src等必要属性
m.appendReplacement(sb, tagWithProp);
}else if ("a".equals(tag)) {
//a标签保留属性,可进一步处理删除无用属性,仅保留href等必要属性
m.appendReplacement(sb, tagWithProp);
}else{
m.appendReplacement(sb, "<" + tag + ">");
}
}
m.appendTail(sb);
return sb.toString();
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值