Java uses regular to remove all HTML tags

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HtmlUtil {
	    private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // Define the regular expression of script  
	    private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // Define the regular expression of style  
	    private static final String regEx_html = "<[^>]+>"; // Define the regular expression of HTML tags  
	    private static final String regEx_space = "\\s*|\t|\r|\n";//Define the space carriage return line feed  
	    private static final String regEx_nbsp = " ";
	      
	    /**
	     * @param htmlStr
	     * @return
	     * Remove Html tags
	     */  
	    public static String delHTMLTag(String htmlStr) {  
	        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);  
	        Matcher m_script = p_script.matcher(htmlStr);  
	        htmlStr = m_script.replaceAll(""); // filter script tags  
	  
	        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);  
	        Matcher m_style = p_style.matcher(htmlStr);  
	        htmlStr = m_style.replaceAll(""); // filter style tags  
	  
	        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);  
	        Matches m_html = p_html.matcher (htmlStr);  
	        htmlStr = m_html.replaceAll(""); // filter html tags  
	  
	        Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);  
	        Matcher m_space = p_space.matcher(htmlStr);  
	        htmlStr = m_space.replaceAll(""); // filter space carriage return tags  
	        
	        Pattern p_nbsp = Pattern.compile(regEx_nbsp, Pattern.CASE_INSENSITIVE);  
	        Matcher m_nbsp = p_nbsp.matcher(htmlStr);  
	        htmlStr = m_nbsp.replaceAll(""); // filter spaces and carriage return tags  
	        return htmlStr.trim(); // return text string  
	    }  
	      
	    public static String getTextFromHtml(String htmlStr){  
	        htmlStr = delHTMLTag(htmlStr);  
	        htmlStr = htmlStr.replaceAll(" ", "");  
	        //htmlStr = htmlStr.substring(0, htmlStr.indexOf("。")+1);  
	        return htmlStr;  
	    }  
	      
	    public static void main(String[] args) {  
	        String str = "<div style='text-align:center;'>测试 测试<br/><span style='font-size:14px;'> </span><span style='font-size:18px;'>测试,测试</span><br/></div>";  
	        System.out.println(getTextFromHtml(str));  
	    }  
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325544339&siteId=291194637