這篇文章將為大家詳細(xì)講解有關(guān)Java如何實(shí)現(xiàn)從Html文本中提取純文本的方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
1、應(yīng)用場(chǎng)景:從一份html文件中或從String(是html內(nèi)容)中提取純文本,去掉網(wǎng)頁(yè)標(biāo)簽;
2、代碼一:replaceAll搞定
//從html中提取純文本 public static String StripHT(String strHtml) { String txtcontent = strHtml.replaceAll("?[^>]+>", ""); //剔出的標(biāo)簽 txtcontent = txtcontent.replaceAll("\\s*|\t|\r|\n", "");//去除字符串中的空格,回車,換行符,制表符 return txtcontent; }
3、代碼二:正則表達(dá)式搞定
//從html中提取純文本 public static String Html2Text(String inputString) { String htmlStr = inputString; // 含html標(biāo)簽的字符串 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 { String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定義script的正則表達(dá)式{或