java去除html tags

本文介绍了一种使用Java从字符串中移除HTML标签的方法,并提供了优化数据处理的额外技巧。该方法首先通过正则表达式移除所有的HTML标签,然后处理换行符和特殊字符。此外,还提供了一个更全面的优化函数,可以更细致地去除脚本和样式标签。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     public static String removeHTML(String htmlString)
     {
           // Remove HTML tag from java String   
         String noHTMLString = htmlString.replaceAll("//<.*?//>", "");
 
         // Remove Carriage return from java String
         noHTMLString = noHTMLString.replaceAll("/r", "<br/>");
 
         // Remove New line from java string and replace html break
         noHTMLString = noHTMLString.replaceAll("/n", " ");
         noHTMLString = noHTMLString.replaceAll("/'", "&#39;");
         noHTMLString = noHTMLString.replaceAll("/"", "&quot;");
         return noHTMLString;
     }
 
     public static void main(String[] args) {
 
     String strHTML= "<html>"+
                     "<head>"+
                     "<title>Convert HTML to Text String</title>"+
                     "</head>"+
 
                     "<body>"+
                     "This is HTML String of java's source code  /"my program/""+
                     "</body>"+
                     "</html>";
 
         String stringWithoutHTML=removeHTML(strHTML);
 
         System.out.println(stringWithoutHTML);
     }

 

 

 

 

  1. public static String regEx_script = "<script[^>]*?>[//s//S]*?<///script>";     
  2.  public static String regEx_style = "<style[^>]*?>[//s//S]*?<///style>";    
  3.  public static String regEx_html = "<[^>]+>";   
  4.     
  5.  public static Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);   
  6.  public static Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);   
  7.  public static Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);   
  8.     
  9.  public static String getOptimizedData(String inputString) {   
  10.       if (inputString == null) {   
  11.            return inputString;   
  12.       }   
  13.      
  14.       //stripping script tags whether the tag contains "/n" or "/r" or not.   
  15.       Matcher m_script = p_script.matcher(inputString);   
  16.       String htmlStr = m_script.replaceAll("");   
  17.     
  18.       //stripping style tags whether the tag contains "/n" or "/r" or not.   
  19.       Matcher m_style = p_style.matcher(htmlStr);   
  20.       htmlStr = m_style.replaceAll("");   
  21.     
  22.       //stripping html tags but continue to have the "/n" and "/r" in right place.   
  23.       Matcher m_html = p_html.matcher(htmlStr);   
  24.       htmlStr = m_html.replaceAll("");   
  25.     
  26.       return htmlStr;   
  27.  }   

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值