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

前端之家收集整理的这篇文章主要介绍了使用正则表达式过滤HTML中标签前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Java代码
  1. packagecom.tan.code;
  2. importjava.util.regex.Pattern;
  3. publicclassDeleteHtml{
  4. //去掉文本中的html标签
  5. staticclassHtmlText{
  6. staticStringHtml2Text(StringinputString){
  7. StringhtmlStr=inputString;
  8. StringtextStr="";
  9. java.util.regex.Patternp_script;
  10. java.util.regex.Matcherm_script;
  11. java.util.regex.Patternp_style;
  12. java.util.regex.Matcherm_style;
  13. java.util.regex.Patternp_html;
  14. java.util.regex.Matcherm_html;
  15. java.util.regex.Patternp_html1;
  16. java.util.regex.Matcherm_html1;
  17. try{
  18. StringregEx_script="<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";//定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
  19. //}
  20. StringregEx_style="<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";//定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
  21. StringregEx_html="<[^>]+>";//定义HTML标签的正则表达式
  22. StringregEx_html1="<[^>]+";
  23. p_script=Pattern.compile(regEx_script,
  24. Pattern.CASE_INSENSITIVE);
  25. m_script=p_script.matcher(htmlStr);
  26. htmlStr=m_script.replaceAll("");//过滤script标签
  27. p_style=Pattern
  28. .compile(regEx_style,Pattern.CASE_INSENSITIVE);
  29. m_style=p_style.matcher(htmlStr);
  30. htmlStr=m_style.replaceAll("");//过滤style标签
  31. p_html=Pattern.compile(regEx_html,250)"> m_html=p_html.matcher(htmlStr);
  32. htmlStr=m_html.replaceAll("");//过滤html标签
  33. p_html1=Pattern
  34. .compile(regEx_html1,250)"> m_html1=p_html1.matcher(htmlStr);
  35. htmlStr=m_html1.replaceAll(""); textStr=htmlStr;
  36. }catch(Exceptione){
  37. System.err.println("Html2Text:"+e.getMessage());
  38. }
  39. returntextStr;//返回文本字符串
  40. }
原文链接:https://www.f2er.com/regex/359831.html

猜你在找的正则表达式相关文章