java中利用正则去除html标签

java用正则去除html标签

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.xz.cxzy.utils;  
  2.   
  3. import java.util.regex.Matcher;  
  4. import java.util.regex.Pattern;  
  5.   
  6. public class HtmlUtil {  
  7.     private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"// 定义script的正则表达式  
  8.     private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"// 定义style的正则表达式  
  9.     private static final String regEx_html = "<[^>]+>"// 定义HTML标签的正则表达式  
  10.     private static final String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符  
  11.       
  12.     /** 
  13.      * @param htmlStr 
  14.      * @return 
  15.      *  删除Html标签 
  16.      */  
  17.     public static String delHTMLTag(String htmlStr) {  
  18.         Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);  
  19.         Matcher m_script = p_script.matcher(htmlStr);  
  20.         htmlStr = m_script.replaceAll(""); // 过滤script标签  
  21.   
  22.         Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);  
  23.         Matcher m_style = p_style.matcher(htmlStr);  
  24.         htmlStr = m_style.replaceAll(""); // 过滤style标签  
  25.   
  26.         Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);  
  27.         Matcher m_html = p_html.matcher(htmlStr);  
  28.         htmlStr = m_html.replaceAll(""); // 过滤html标签  
  29.   
  30.         Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);  
  31.         Matcher m_space = p_space.matcher(htmlStr);  
  32.         htmlStr = m_space.replaceAll(""); // 过滤空格回车标签  
  33.         return htmlStr.trim(); // 返回文本字符串  
  34.     }  
  35.       
  36.     public static String getTextFromHtml(String htmlStr){  
  37.         htmlStr = delHTMLTag(htmlStr);  
  38.         htmlStr = htmlStr.replaceAll("&nbsp;""");  
  39.         htmlStr = htmlStr.substring(0, htmlStr.indexOf("。")+1);  
  40.         return htmlStr;  
  41.     }  
  42.       
  43.     public static void main(String[] args) {  
  44.         String str = "<div style='text-align:center;'> 整治“四风”   清弊除垢<br/><span style='font-size:14px;'> </span><span style='font-size:18px;'>公司召开党的群众路线教育实践活动动员大会</span><br/></div>";  
  45.         System.out.println(getTextFromHtml(str));  
  46.     }  
  47. }  

注:\n 回车(\u000a)
\t 水平制表符(\u0009)
\s 空格(\u0008)
\r 换行(\u000d)*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值