格式化html格式的java工具类

441 阅读1分钟

一、前言

日常工作中经常会用到处理html格式的文本,每次都要重新写,重新写一堆蛇皮的正则,头秃;故记录下一个工具类,日常使用;

二、常见的正则表达式

表达式描述
^[a-z0-9_-]{3,16}$用户名
^[a-z0-9_-]{6,18}$ 密码
^([a-z0-9_.-]+)@([\da-z.-]+).([a-z.]{2,6})$邮箱
[\u4e00-\u9fa5]匹配中文的表达式

三、代码

废话不说,直接上代码


public class HtmlTextParseUtils {

    /**
     * 解析html——》Text
     * @param inputHtmlText
     * @return
     */
    public static String htmlToText(String inputHtmlText){
        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;
        String textStr = "";
        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 = "<[^>]+>";
            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(inputHtmlText);
            // 过滤script标签
            inputHtmlText = m_script.replaceAll("");
            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(inputHtmlText);
            // 过滤style标签
            inputHtmlText = m_style.replaceAll("");
            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(inputHtmlText);
            // 过滤html标签
            inputHtmlText = m_html.replaceAll("");
            textStr =  inputHtmlText;
        }catch (Exception e){
            //剔除空格行
            textStr=textStr.replaceAll("[ ]+", " ");
            textStr=textStr.replaceAll("(?m)^\s*$(\n|\r\n)", "");
            // 返回文本字符串
            return textStr;
        }

        return textStr;
    }


}

四、总结

正则在处理数字、符号、字母等非常好用,但是如果处理纯中文文本就显的很难;期待有其他好的方式可以处理中文文本;