java正則表達式去除html標籤

當咱們用ckeditor或其餘一些在線文本編輯器的時候 內容裏會有不少的標籤
以下片斷:
<p><img alt="" src="/img/uploadImg/20131218/0fd741e1-cc75-459c-a8b5-bbaebcfcc637.jpg"
style="height:494px; width:460px" /></p>

<p>生命的旅途,一程有一程的風景,一程有一程的盛放。打開心靈的窗子,
靜看時光旖旎着一曲花開花落,用一種看山是山,看水是水的境界來生活就會快樂,
人生的最美,即是來自心靈深處的通透與清歡。</p>

<p>——題記</p>

<p>喜歡在飄雪的午後,盈一眸恬靜,書一抹情懷,看那雪花落入紅塵最深處。
暫離塵世喧囂,將心靈放空,盡情的體會那份曠達與純淨。生命的旅途中,
會有不期而遇的欣喜,也會有痛徹心扉的清醒,一地落紅,氤氳了冷暖;一樹梅開,
繾綣了浮華,雪如拂塵,能撣去俗世的無奈,也能讓靈魂淨化。</p>
包含一些圖片,段落,換行等html標籤
若是要進行統計字數,則就須要去除這些標籤。用java正則 以下代碼:
/**
 * 刪除Html標籤
 * 
 * @param inputString
 * @return
 */
public static String htmlRemoveTag(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;
	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]*?>"; 
		String regEx_html = "<[^>]+>"; // 定義HTML標籤的正則表達式
		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標籤
		textStr = htmlStr;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return textStr;// 返回文本字符串
}
相關文章
相關標籤/搜索