打赏 jQuery火箭图标返回顶部代码

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

 1 /**
 2      * 去掉文本中的html标签
 3      *
 4      * @param inputString
 5      * @return
 6      */
 7     public static String html2Text(String inputString) {
 8         if (StringUtils.isEmpty(inputString)) {
 9             return null;
10         }
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             // 替换&amp;nbsp;
52             textStr = textStr.replaceAll("&amp;", "").replaceAll("nbsp;", "");
53 
54         } catch (Exception e) {
55             System.err.println("Html2Text: " + e.getMessage());
56         }
57 
58         return textStr;// 返回文本字符串
59     }
posted @ 2018-07-05 21:40  浪漫De刺猬  阅读(1340)  评论(0编辑  收藏  举报