使用正则表达式过滤HTML中标签

来源:互联网 发布:开发长沙软件外包 编辑:程序博客网 时间:2024/05/22 07:59
Java代码  收藏代码
  1. package com.tan.code;  
  2.   
  3. import java.util.regex.Pattern;  
  4.   
  5. public class DeleteHtml {  
  6.   
  7.     //去掉文本中的html标签  
  8.       
  9.     public static class HtmlText {  
  10.         public static String Html2Text(String inputString) {  
  11.             String htmlStr = inputString;  
  12.             String textStr = "";  
  13.             java.util.regex.Pattern p_script;  
  14.             java.util.regex.Matcher m_script;  
  15.             java.util.regex.Pattern p_style;  
  16.             java.util.regex.Matcher m_style;  
  17.             java.util.regex.Pattern p_html;  
  18.             java.util.regex.Matcher m_html;  
  19.   
  20.             java.util.regex.Pattern p_html1;  
  21.             java.util.regex.Matcher m_html1;  
  22.   
  23.             try {  
  24.                 String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"// 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>  
  25.                                                                                                             // }  
  26.                 String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"// 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>  
  27.                                                                                                         // }  
  28.                 String regEx_html = "<[^>]+>"// 定义HTML标签的正则表达式  
  29.                 String regEx_html1 = "<[^>]+";  
  30.                 p_script = Pattern.compile(regEx_script,  
  31.                         Pattern.CASE_INSENSITIVE);  
  32.                 m_script = p_script.matcher(htmlStr);  
  33.                 htmlStr = m_script.replaceAll(""); // 过滤script标签  
  34.   
  35.                 p_style = Pattern  
  36.                         .compile(regEx_style, Pattern.CASE_INSENSITIVE);  
  37.                 m_style = p_style.matcher(htmlStr);  
  38.                 htmlStr = m_style.replaceAll(""); // 过滤style标签  
  39.   
  40.                 p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);  
  41.                 m_html = p_html.matcher(htmlStr);  
  42.                 htmlStr = m_html.replaceAll(""); // 过滤html标签  
  43.   
  44.                 p_html1 = Pattern  
  45.                         .compile(regEx_html1, Pattern.CASE_INSENSITIVE);  
  46.                 m_html1 = p_html1.matcher(htmlStr);  
  47.                 htmlStr = m_html1.replaceAll(""); // 过滤html标签  
  48.   
  49.                 textStr = htmlStr;  
  50.   
  51.             } catch (Exception e) {  
  52.                 System.err.println("Html2Text: " + e.getMessage());  
  53.             }  
  54.   
  55.             return textStr;// 返回文本字符串  
  56.         }  
  57.     }  
  58. }  

 

0 0
原创粉丝点击