業務場景:
如一篇使用富文本編輯器編輯的新聞稿,需要在列表頁面截取前200字作為摘要,此時需要去除html標簽,截取真正的文本部分。
/**
* 刪除Html標簽
*/
public static String removeHtmlTag(String htmlStr) {
//定義script的正則表達式{或<script[^>]*?>[\\s\\S]*?<\\/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]*?>";
//定義HTML標簽的正則表達式
String regEx_html = "<[^>]+>";
//定義一些特殊字符的正則表達式 如:
String regEx_special = "\\&[a-zA-Z]{1,10};";
//1.過濾script標簽
Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll("");
//2.過濾style標簽
Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
Matcher m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll("");
//3.過濾html標簽
Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll("");
//4.過濾特殊標簽
Pattern p_special = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE);
Matcher m_special = p_special.matcher(htmlStr);
htmlStr = m_special.replaceAll("");
return htmlStr;
}
使用正則表達式去除html中的元素屬性
- 業務場景:
如某網站歷史數據中有很多富文本編輯器編輯的新聞稿,里面定義了很多行內樣式,現開發了新網站,統一定義了樣式,進行數據遷移時需要去除這些行內樣式,但保留標簽。 - 代碼實現:
private static final String regEx_tag = "<(\\w[^>|\\s]*)[\\s\\S]*?>";
public static String removeEleProp(String htmlStr) {
Pattern p = Pattern.compile(regEx_tag, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(htmlStr);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String tagWithProp= m.group(0);
String tag =m.group(1);
if ("img".equals(tag)) {
//img標簽保留屬性,可進一步處理刪除無用屬性,僅保留src等必要屬性
m.appendReplacement(sb, tagWithProp);
}else if ("a".equals(tag)) {
//a標簽保留屬性,可進一步處理刪除無用屬性,僅保留href等必要屬性
m.appendReplacement(sb, tagWithProp);
}else{
m.appendReplacement(sb, "<" + tag + ">");
}
}
m.appendTail(sb);
return sb.toString();
}
使用方法:
jsoup Cookbook(中文版)
jsoup官網(en)
————————————————
版權聲明:本文為CSDN博主「fukaiit」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/fukaiit/article/details/84262471