清除字符串中HTML标签

        在使用Editor(所见即所得编辑器)的时候,有时候可能会碰到需要在后台修改编辑器的内容,而且这些内容还都是HTML格式的数据,这个时候如果需要定位到某个标签的话就比较困难,毕竟是后台语言,不像前端的js一样可以在页面上直接取到某个标签,今天就分析一下使用Java如何操作HTML格式的字符串。

  1.     /**
  2.      * 清除html标签
  3.      * @param line
  4.      * @return
  5.      */
  6.     private static String removeHtmlTag(String line) {
  7.         if (line == null) {
  8.             return null;
  9.         }
  10.         String htmlStr = line;
  11.         String textStr = "";
  12.         try {
  13.             // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
  14.             String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
  15.             // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
  16.             String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
  17.             // 定义HTML标签的正则表达式
  18.             String regEx_html = "<[^>]+>";
  19.             // 定义一些特殊字符的正则表达式 如:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
  20.             String regEx_special = "\\&[a-zA-Z]{1,10};";
  21.             // 过滤script标签
  22.             Pattern p_script = Pattern.compile(regEx_script, 2);
  23.             Matcher m_script = p_script.matcher(htmlStr);
  24.             // 过滤style标签
  25.             htmlStr = m_script.replaceAll("");
  26.             Pattern p_style = Pattern.compile(regEx_style, 2);
  27.             Matcher m_style = p_style.matcher(htmlStr);
  28.             // 过滤html标签
  29.             htmlStr = m_style.replaceAll("");
  30.             Pattern p_html = Pattern.compile(regEx_html, 2);
  31.             Matcher m_html = p_html.matcher(htmlStr);
  32.             // 过滤特殊标签
  33.             htmlStr = m_html.replaceAll("");
  34.             Pattern p_special = Pattern.compile(regEx_special, 2);
  35.             Matcher m_special = p_special.matcher(htmlStr);
  36.             htmlStr = m_special.replaceAll("");
  37.             textStr = htmlStr.replace("\\n", "").replace("\\t", " ").replace("\t", " ");
  38.         } catch (Exception e) {
  39.             e.printStackTrace();
  40.         }
  41.         return textStr;
  42.     }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值