Java去除掉HTML里面所有标签的两种方法——开源jar包和自己写正则表达式
生活随笔
收集整理的這篇文章主要介紹了
Java去除掉HTML里面所有标签的两种方法——开源jar包和自己写正则表达式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java去除掉HTML里面所有標簽,主要就兩種,要么用開源的jar處理,要么就自己寫正則表達式。自己寫的話,可能處理不全一些自定義的標簽。企業應用基本都是能找開源就找開源,實在不行才自己寫……
1,開源的,我目前找到的就是Jsoup包:
public static String getTextFromTHML(String htmlStr) {Document doc = Jsoup.parse(htmlStr);String text = doc.text();// remove extra white spaceStringBuilder builder = new StringBuilder(text);int index = 0;while(builder.length()>index){char tmp = builder.charAt(index);if(Character.isSpaceChar(tmp) || Character.isWhitespace(tmp)){builder.setCharAt(index, ' ');}index++;}text = builder.toString().replaceAll(" +", " ").trim();return text;}?
2,自己寫的話,百度一搜一大堆,這里只是借用一下:
public static String removeTag(String htmlStr) {String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // scriptString regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // styleString regEx_html = "<[^>]+>"; // HTML tagString regEx_space = "\\s+|\t|\r|\n";// other characters Pattern p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);Matcher m_script = p_script.matcher(htmlStr);htmlStr = m_script.replaceAll("");Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);Matcher m_style = p_style.matcher(htmlStr);htmlStr = m_style.replaceAll("");Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);Matcher m_html = p_html.matcher(htmlStr);htmlStr = m_html.replaceAll("");Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);Matcher m_space = p_space.matcher(htmlStr);htmlStr = m_space.replaceAll(" ");return htmlStr;}?
?
轉載于:https://www.cnblogs.com/wytings/p/4580065.html
總結
以上是生活随笔為你收集整理的Java去除掉HTML里面所有标签的两种方法——开源jar包和自己写正则表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (二)盒子模型
- 下一篇: Android邮件发送详解