1. 使用正則表達式去除html標籤
/**
* 去除Html標籤
*
* @param html
* html內容
* @return 去除標籤後的文本
*/
public static String dislodgeHtmlLabel(String html) {
if (Objects.isNull(html)) {
return "";
}
// 過濾script標籤
Pattern pscript = Pattern.compile("<script[^>]*?>[\\s\\S]*?<\\/script>", Pattern.CASE_INSENSITIVE);
// 過濾style的正則
Pattern pstyle = Pattern.compile("<style[^>]*?>[\\s\\S]*?<\\/style>", Pattern.CASE_INSENSITIVE);
// 過濾html標籤的正則
Pattern phtml = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);
// 執行過濾script標籤
Matcher mscript = pscript.matcher(html);
html = mscript.replaceAll("");
// 執行過濾style標籤
Matcher mstyle = pstyle.matcher(html);
html = mstyle.replaceAll("");
// 執行過濾html標籤
Matcher mHtml = phtml.matcher(html);
html = mHtml.replaceAll("");
// 返回文本字符串
return html.trim();
}
2. 使用Jsoup組件去除html標籤
pom文件:
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.12.1</version>
</dependency>
/**
* 去除Html標籤
*
* @param html
* html內容
* @return 去除標籤後的文本
*/
public static String wipeOffHtmlLabel(String html) {
// null則返回空字符串
if (Objects.isNull(html)) {
return "";
}
// 異常返回自身
try {
return Jsoup.parse(html).text();
} catch (Exception e) {
return html;
}
}
3. 運行情況
public static void main(String[] args) {
// 未閉合的html標籤
String notClosed = "<p>你大爺的</p><p><a href=\"http://www.baidu.com\" rel=\"noopener noreferrer\" target=\"_blank\">百度</a><br><br><img alt=\"\" src=\"http://www.baidu.c";
// 正常閉合html標籤
String normal = "<p><strong><span style=\"font-size: 18px;\">你是個傻小子</span></strong></p>";
// 1. 使用正則表達式
String notClosed1 = dislodgeHtmlLabel(notClosed);
String normal1 = dislodgeHtmlLabel(normal);
System.out.println(notClosed1);
System.out.println(normal1);
System.out.println("*****************************************");
// 2. 使用Jsoup組件
String notClosed2 = wipeOffHtmlLabel(notClosed);
String normal2 = wipeOffHtmlLabel(normal);
System.out.println(notClosed2);
System.out.println(normal2);
}
結果:
4. 結論
- 完全閉合的標籤推薦使用正則表達式,因爲是輕量級的。
- 如果是從數據庫中查出截斷的html文本,最好使用Jsoup組件,支持去除未閉合的標籤。