当要提取网页中的纯文本内容,将这些内容展现在自己的页面上,发现自己的页面html格式被破坏了,原来提取的内容中有类似于 "<font>,...."这类的html标签,从而导致浏览器这些标签破坏自己的页面格式,所以在提取完内容后应该将其中的标签都过滤掉,此时正则表达式可以很好的解决此问题。
//定义script的正则表达式
String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>";
//定义style的正则表达式{或<style>]*?>[/s/S]*?<//style> }
String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>";
//定义除了<b>和</b>以外的HTML标签的正则表达式
//String regEx_html = "<[^>]+>";
String regEx_html = "<(?!/?b>)[^>]+>";
//过滤script标签
p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll("");
//过滤style标签
p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll("");
//过滤HTML标签
p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll("");
//替换<b>为<font>
htmlStr = htmlStr.replaceAll("<b>", "<font color='red'>");
htmlStr = htmlStr.replaceAll("</b>", "</font>");
textStr = htmlStr;
本文介绍了一种使用正则表达式从提取的网页内容中去除HTML标签的方法,包括如何排除特定标签及替换其他标签。
3204

被折叠的 条评论
为什么被折叠?



