`
ttitfly
  • 浏览: 616321 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

过滤Html标签(转)

    博客分类:
  • java
阅读更多
java 代码
  1. public  String html2Text(String inputString) {   
  2.       String htmlStr = inputString; //含html标签的字符串   
  3.       String textStr ="";   
  4.       java.util.regex.Pattern p_script;   
  5.       java.util.regex.Matcher m_script;   
  6.       java.util.regex.Pattern p_style;   
  7.       java.util.regex.Matcher m_style;   
  8.       java.util.regex.Pattern p_html;   
  9.       java.util.regex.Matcher m_html;   
  10.          
  11.       try {   
  12.        String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"//定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }   
  13.        String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"//定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }   
  14.           String regEx_html = "<[^>]+>"//定义HTML标签的正则表达式   
  15.           
  16.           p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);   
  17.           m_script = p_script.matcher(htmlStr);   
  18.           htmlStr = m_script.replaceAll(""); //过滤script标签   
  19.   
  20.           p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);   
  21.           m_style = p_style.matcher(htmlStr);   
  22.           htmlStr = m_style.replaceAll(""); //过滤style标签   
  23.           
  24.           p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);   
  25.           m_html = p_html.matcher(htmlStr);   
  26.           htmlStr = m_html.replaceAll(""); //过滤html标签   
  27.           
  28.        textStr = htmlStr;   
  29.           
  30.       }catch(Exception e) {   
  31.                   System.err.println("Html2Text: " + e.getMessage());   
  32.       }   
  33.          
  34.       return textStr;//返回文本字符串   
  35.     }     
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics