Java去除掉HTML里面所有标签,
2015-11-24 16:41
344 查看
Java去除掉HTML里面所有标签的两种方法——开源jar包和自己写正则表达式
时间 2015-06-16 10:17:20博客园精华区
原文 http://www.cnblogs.com/wytings/p/4580065.html 主题
Java HTML
开源
主要就两种,要么用开源的jar处理,要么就自己写正则表达式。自己写的话,可能处理不全一些自定义的标签。企业应用基本都是能找开源就找开源,实在不行才自己写……
1,开源的,我目前找到的就是Jsoup包:
public static String getTextFromTHML(String htmlStr) { Document doc = Jsoup.parse(htmlStr); String text = doc.text(); // remove extra white space StringBuilder 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>"; // script String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // style String regEx_html = "<[^>]+>"; // HTML tag String 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; }
相关文章推荐
- 基于注释的Spring cache 缓存介绍
- 如何使用java的正则表达式提取html标签?
- 《JAVA与模式》之合成模式
- Quartz Spring与Spring Task总结
- 教你学会java基础多线程系列文章之基础篇
- Java正则表达式提取html纯文本
- Java基础---IO流(上)
- ubuntu中netbean ide中文乱码
- 数组的基本操作(一)
- java正则表达式取得html标签内的内容
- Java记录 -86- Reflection API的使用示例进阶2
- 我的第五个java程序 每过10秒读取一次天气 并把天气更新到mysql数据库里
- Spring Data JPA 持久层开发
- MyEclipse Import 工程 Unknown Faceted Project Problem (Java Version Mismatch) 问题解决!
- Eclipse配置JDK的源代码的src.zip
- 浅谈Java中的hashcode方法
- 解决eclipse编译的几种方法
- spring mvc注解例子
- java程序中调用scilab
- java正则表达式修改html标签中属性