从网页获取的自己关心的内容后,有些标签会有内联样式,例如
<span style="font-size:16px;font-family:'Microsoft YaHei';">
如何只要span而不要style
style
其他的div什么的都一样。
这个样式是包含(前面有个空格) style=”中间任意多个字符串后面一个”。
来看正则表达式的写法
String regEx = " style=\"(.*?)\"";
使用到的正则规则
关键代码
/**
* 清除公告中的style
*
* @param content 公告内容
* @return 字符串结果集
*/
public static String removeContentStyle(String content) {
String regEx = " style=\'(.*?)\'";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(content);
if (m.find()) {
content = m.replaceAll("");
}
String regEx2 = " style=\"([\\s\\S]*?)\"";
Pattern p2 = Pattern.compile(regEx2);
Matcher m2 = p2.matcher(content);
if (m2.find()) {
content = m2.replaceAll("");
}
String regEx3 = " border=\"(.*?)\"";
Pattern p3 = Pattern.compile(regEx3);
Matcher m3 = p3.matcher(content);
if (m3.find()) {
content = m3.replaceAll(" border=\"0\" ");
}
/* String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
Pattern p3 = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
Matcher m3 = p3.matcher(content);
content = m3.replaceAll("");*/
/*String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(content);
content = m_html.replaceAll(""); //过滤html标签*/
return content;
}
参考链接:https://blog.csdn.net/frankcheng5143/article/details/52815625