java正則表達式去除html中所有的標簽和特殊HTML字符(以&開頭的)


來源於:https://www.androiddev.net/java%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E5%8E%BB%E9%99%A4html%E4%B8%AD%E6%89%80%E6%9C%89%E7%9A%84%E6%A0%87%E7%AD%BE%E5%92%8C%E7%89%B9%E6%AE%8Ahtml%E5%AD%97%E7%AC%A6%EF%BC%88%E4%BB%A5/

 

 

package com.comcons.utils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Pattern;

public class ReduceHtml2Text {

/**
* 刪除Html標簽
* @param inputString
* @return
*/
public static String removeHtmlTag(String inputString) {
if (inputString == null)
return null;
String htmlStr = inputString; // 含html標簽的字符串
String textStr = "";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
java.util.regex.Pattern p_style;
java.util.regex.Matcher m_style;
java.util.regex.Pattern p_html;
java.util.regex.Matcher m_html;
java.util.regex.Pattern p_special;
java.util.regex.Matcher m_special;
try {
//定義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 = "<[^>]+>";
// 定義一些特殊字符的正則表達式 如:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
String regEx_special = "\\&[a-zA-Z]{1,10};";

p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 過濾script標簽
p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 過濾style標簽
p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 過濾html標簽
p_special = Pattern.compile(regEx_special, Pattern.CASE_INSENSITIVE);
m_special = p_special.matcher(htmlStr);
htmlStr = m_special.replaceAll(""); // 過濾特殊標簽
textStr = htmlStr;
} catch (Exception e) {
e.printStackTrace();
}
return textStr;// 返回文本字符串
}

/**
* 測試用的main函數
* @param args
*/
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
try {
FileReader fr = new FileReader("D:/test.html");
BufferedReader br = new BufferedReader(fr);
String s = "";
while((s = br.readLine())!=null){
sb.append(s);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String ssss = ReduceHtml2Text.removeHtmlTag(sb.toString());
System.out.println(ssss);
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM