加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 00:57:12 所属栏目:百科 来源:网络整理
导读:Java代码 package com.tan.code; import java.util.regex.Pattern; public class DeleteHtml{ //去掉文本中的html标签 static class HtmlText{ static StringHtml2Text(StringinputString){ StringhtmlStr=inputString; StringtextStr= "" ; java.util.regex
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[^>]*?>[sS]*?<[s]*?/[s]*?script[s]*?>";//定义script的正则表达式{或<script[^>]*?>[sS]*?</script>
  19. //}
  20. StringregEx_style="<[s]*?style[^>]*?>[sS]*?<[s]*?/[s]*?style[s]*?>";//定义style的正则表达式{或<style[^>]*?>[sS]*?</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. }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读