Html2Text.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package com.yihu.wlyy.util;
  2. import java.util.regex.Pattern;
  3. /**
  4. * Created by Reece on 2017/3/6.
  5. */
  6. public class Html2Text {
  7. public static String Html2Text(String inputString){
  8. String htmlStr = inputString; //含html标签的字符串
  9. String textStr ="";
  10. java.util.regex.Pattern p_script;
  11. java.util.regex.Matcher m_script;
  12. java.util.regex.Pattern p_style;
  13. java.util.regex.Matcher m_style;
  14. java.util.regex.Pattern p_html;
  15. java.util.regex.Matcher m_html;
  16. try{
  17. String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }
  18. String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }
  19. String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
  20. p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
  21. m_script = p_script.matcher(htmlStr);
  22. htmlStr = m_script.replaceAll(""); //过滤script标签
  23. p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
  24. m_style = p_style.matcher(htmlStr);
  25. htmlStr = m_style.replaceAll(""); //过滤style标签
  26. p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
  27. m_html = p_html.matcher(htmlStr);
  28. htmlStr = m_html.replaceAll(""); //过滤html标签
  29. textStr = htmlStr;
  30. }catch(Exception e){
  31. // Manager.log.debug("neiNewsAction","Html2Text: " + e.getMessage());
  32. }
  33. return textStr;//返回文本字符串
  34. }
  35. }