欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

StringUtil工具类验证手机号,邮箱,身份证号,实现检查密码强弱等

程序员文章站 2022-03-19 15:58:56
import java.io.PrintWriter;import java.io.StringWriter;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.regex.Ma....
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

public class StringUtil extends StringUtils {
    private static final char SEPARATOR = '_';
    private static final String CHARSET = "UTF-8";
    private static List<Pattern> patterns = null;

    public StringUtil() {
    }

    public static byte[] getBytes(String str) {
        if (str != null) {
            try {
                return str.getBytes("UTF-8");
            } catch (UnsupportedEncodingException var2) {
                return null;
            }
        } else {
            return null;
        }
    }

    public static String toString(byte[] bytes) {
        try {
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException var2) {
            return "";
        }
    }

    public static Boolean toBoolean(Object val) {
        return val == null ? false : BooleanUtils.toBoolean(val.toString()) || "1".equals(val.toString());
    }

    public static String toString(Object obj, String defaultVal) {
        return obj == null ? defaultVal : obj.toString();
    }

    public static boolean inString(String str, String... strs) {
        if (str != null) {
            String[] var2 = strs;
            int var3 = strs.length;

            for(int var4 = 0; var4 < var3; ++var4) {
                String s = var2[var4];
                if (str.equals(trim(s))) {
                    return true;
                }
            }
        }

        return false;
    }

    public static Double toDouble(Object val) {
        if (val == null) {
            return 0.0D;
        } else {
            try {
                return Double.valueOf(trim(val.toString()));
            } catch (Exception var2) {
                return 0.0D;
            }
        }
    }

    public static Float toFloat(Object val) {
        return toDouble(val).floatValue();
    }

    public static Long toLong(Object val) {
        return toDouble(val).longValue();
    }

    public static Integer toInteger(Object val) {
        return toLong(val).intValue();
    }

    public static String ellipsis(String str, int length) {
        if (str == null) {
            return "";
        } else {
            try {
                StringBuilder sb = new StringBuilder();
                int currentLength = 0;
                char[] var4 = replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray();
                int var5 = var4.length;

                for(int var6 = 0; var6 < var5; ++var6) {
                    char c = var4[var6];
                    currentLength += String.valueOf(c).getBytes("GBK").length;
                    if (currentLength > length - 3) {
                        sb.append("...");
                        break;
                    }

                    sb.append(c);
                }

                return sb.toString();
            } catch (UnsupportedEncodingException var8) {
                var8.printStackTrace();
                return "";
            }
        }
    }

    public static String replaceHtml(String html) {
        if (isBlank(html)) {
            return "";
        } else {
            String regEx = "<.+?>";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(html);
            String s = m.replaceAll("");
            return s;
        }
    }

    public static String escapeHtml(String html) {
        return StringEscapeUtils.escapeHtml4(html);
    }

    public static String unescapeHtml(String htmlEscaped) {
        return StringEscapeUtils.unescapeHtml4(htmlEscaped);
    }

    public static String escapeXml(String xml) {
        return StringEscapeUtils.escapeXml11(xml);
    }

    public static String unescapeXml(String xmlEscaped) {
        return StringEscapeUtils.unescapeXml(xmlEscaped);
    }

    public static String appendURIParam(String url, String name, String value) {
        url = url + (url.indexOf(63) == -1 ? '?' : '&');
        url = url + EncodeUtil.encodeUrl(name) + '=' + EncodeUtil.encodeUrl(value);
        return url;
    }

    public static String appendURIParam(String url, Map<String, String> map) {
        Entry entry;
        for(Iterator it = map.entrySet().iterator(); it.hasNext(); url = appendURIParam(url, (String)entry.getKey(), (String)entry.getValue())) {
            entry = (Entry)it.next();
        }

        return url;
    }

    public static String camelToUnderline(String param) {
        if (param != null && !"".equals(param.trim())) {
            int len = param.length();
            StringBuilder sb = new StringBuilder(len);

            for(int i = 0; i < len; ++i) {
                char c = param.charAt(i);
                if (Character.isUpperCase(c)) {
                    sb.append('_');
                    sb.append(Character.toLowerCase(c));
                } else {
                    sb.append(c);
                }
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    public static String underlineToCamel(String param) {
        if (param != null && !"".equals(param.trim())) {
            StringBuilder sb = new StringBuilder(param);
            Matcher mc = Pattern.compile(String.valueOf('_')).matcher(param);
            int var3 = 0;

            while(mc.find()) {
                int position = mc.end() - var3++;
                sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    public static String formatBytes(long size) {
        int bytes = 1024;
        if (size < (long)bytes) {
            return size + "Byte";
        } else {
            size /= (long)bytes;
            if (size < (long)bytes) {
                return size + "K";
            } else {
                size /= (long)bytes;
                if (size < (long)bytes) {
                    size *= 100L;
                    return size / 100L + "." + size % 100L + "M";
                } else {
                    size = size * 100L / (long)bytes;
                    return size / 100L + "." + size % 100L + "G";
                }
            }
        }
    }

    public static String formatMobile(String mobile) {
        return isEmpty(mobile) ? null : mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    public static String formatBankCard(String bankCard) {
        return isEmpty(bankCard) ? null : bankCard.replaceAll("(\\d{5})\\d{5}\\d{2}(\\d{4})", "$1****$2");
    }

    public static String formatIdCard(String idCard) {
        return isEmpty(idCard) ? null : idCard.replaceAll("(\\d{4})\\d{10}(\\w{4})", "$1*****$2");
    }

    public static boolean matchMobile(String mobile) {
        if (mobile == null) {
            return false;
        } else {
            String regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
            return Pattern.matches(regex, mobile);
        }
    }

    public static boolean matchEmail(String email) {
        if (email == null) {
            return false;
        } else {
            String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?";
            return Pattern.matches(regex, email);
        }
    }

    public static boolean matchDomain(String domain) {
        if (domain == null) {
            return false;
        } else {
            String regex = "^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$";
            return Pattern.matches(regex, domain);
        }
    }

    public static boolean matchIp(String ip) {
        if (ip == null) {
            return false;
        } else {
            String regex = "^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
            return Pattern.matches(regex, ip);
        }
    }

    public static boolean matchHttpUrl(String url) {
        if (url == null) {
            return false;
        } else {
            String regex = "^(?=^.{3,255}$)(http(s)?:\\/\\/)?(www\\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\\d+)*(\\/\\w+\\.\\w+)*([\\?&]\\w+=\\w*)*$";
            return Pattern.matches(regex, url);
        }
    }

    public static boolean matchBankCard(String bankCard) {
        if (bankCard == null) {
            return false;
        } else if (bankCard.length() >= 15 && bankCard.length() <= 19) {
            char bit = getBankCardCheckCode(bankCard.substring(0, bankCard.length() - 1));
            if (bit == 'N') {
                return false;
            } else {
                return bankCard.charAt(bankCard.length() - 1) == bit;
            }
        } else {
            return false;
        }
    }

    public static char getBankCardCheckCode(String nonCheckCodeBankCard) {
        if (nonCheckCodeBankCard != null && nonCheckCodeBankCard.trim().length() != 0 && nonCheckCodeBankCard.matches("\\d+")) {
            char[] chs = nonCheckCodeBankCard.trim().toCharArray();
            int luhmSum = 0;
            int i = chs.length - 1;

            for(int j = 0; i >= 0; ++j) {
                int k = chs[i] - 48;
                if (j % 2 == 0) {
                    k *= 2;
                    k = k / 10 + k % 10;
                }

                luhmSum += k;
                --i;
            }

            return luhmSum % 10 == 0 ? '0' : (char)(10 - luhmSum % 10 + 48);
        } else {
            return 'N';
        }
    }

    private static List<Object[]> getXssPatternList() {
        List<Object[]> ret = new ArrayList();
        ret.add(new Object[]{"<(no)?script[^>]*>.*?</(no)?script>", 2});
        ret.add(new Object[]{"eval\\((.*?)\\)", 42});
        ret.add(new Object[]{"expression\\((.*?)\\)", 42});
        ret.add(new Object[]{"(javascript:|vbscript:|view-source:)*", 2});
        ret.add(new Object[]{"<(\"[^\"]*\"|'[^']*'|[^'\">])*>", 42});
        ret.add(new Object[]{"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*", 42});
        ret.add(new Object[]{"<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatuschange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", 42});
        return ret;
    }

    private static List<Pattern> getPatterns() {
        if (patterns == null) {
            List<Pattern> list = new ArrayList();
            String regex = null;
            Integer flag = null;
            int arrLength = false;
            Iterator var4 = getXssPatternList().iterator();

            while(var4.hasNext()) {
                Object[] arr = (Object[])var4.next();
                int arrLength = arr.length;

                for(int i = 0; i < arrLength; ++i) {
                    regex = (String)arr[0];
                    flag = (Integer)arr[1];
                    list.add(Pattern.compile(regex, flag));
                }
            }

            patterns = list;
        }

        return patterns;
    }

    public static String stripXss(String value) {
        if (isNotBlank(value)) {
            Matcher matcher = null;
            Iterator var2 = getPatterns().iterator();

            while(var2.hasNext()) {
                Pattern pattern = (Pattern)var2.next();
                matcher = pattern.matcher(value);
                if (matcher.find()) {
                    value = matcher.replaceAll("");
                }
            }

            value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        }

        return value;
    }

    public static String checkPassword(String passwordStr) {
        String regexZ = "\\d*";
        String regexS = "[a-zA-Z]+";
        String regexT = "\\W+$";
        String regexZT = "\\D*";
        String regexST = "[\\d\\W]*";
        String regexZS = "\\w*";
        String regexZST = "[\\w\\W]*";
        if (passwordStr.matches(regexZ)) {
            return "弱";
        } else if (passwordStr.matches(regexS)) {
            return "弱";
        } else if (passwordStr.matches(regexT)) {
            return "弱";
        } else if (passwordStr.matches(regexZT)) {
            return "中";
        } else if (passwordStr.matches(regexST)) {
            return "中";
        } else if (passwordStr.matches(regexZS)) {
            return "中";
        } else {
            return passwordStr.matches(regexZST) ? "强" : passwordStr;
        }
    }

    public static String getExceptionToString(Throwable e) {
        if (e == null) {
            return "";
        } else {
            StringWriter stringWriter = new StringWriter();
            e.printStackTrace(new PrintWriter(stringWriter));
            return stringWriter.toString();
        }
    }

    public static void main(String[] args) {
        System.out.println(matchDomain("515608851@qq.com"));
        System.out.println(matchDomain("www.qq.com"));
        System.out.println(matchDomain("qq.com"));
        System.out.println(matchIp("qq.com"));
        System.out.println(matchIp("192.168.0.1"));
    }
}

 

本文地址:https://blog.csdn.net/qq_40083897/article/details/111975441