StringUtils 工具类

本文介绍了一个用于处理字符串的工具类StringUtils,提供了多种实用的方法,包括验证邮箱、日期、姓名等,同时还涵盖了数字验证、特殊字符过滤及账号加密等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

StringUtils 工具类

处理String类,包括文本输入框的检验
邮箱检验
日期判断
package com.fintech.cuidaren.utils;

import android.annotation.SuppressLint;
import android.util.Log;

import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by:qingwufeiyang on 2013/6/17 10:19
 * Class: StringUtils
 * Description: String 校验工具类;
 */

public class StringUtils {
    /**
     * 验证
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        return s == null || s.length() == 0 || s.equals("null");
    }

    /**
     * is null or its length is 0 or it is made by space
     * <p>
     * <pre>
     * isBlank(null) = true;
     * isBlank(&quot;&quot;) = true;
     * isBlank(&quot;  &quot;) = true;
     * isBlank(&quot;a&quot;) = false;
     * isBlank(&quot;a &quot;) = false;
     * isBlank(&quot; a&quot;) = false;
     * isBlank(&quot;a b&quot;) = false;
     * </pre>
     *
     * @param str
     * @return if string is null or its size is 0 or it is made by space, return
     * true, else return false.
     */
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0);
    }

    /**
     * 验证邮箱的合法性 ^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$
     *
     * @param email
     * @return
     */
    public static boolean isValidEmail(String email) {
        if (isEmpty(email))
            return false;
        String pattern_ = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
        Pattern pattern = Pattern.compile(pattern_);
        Matcher mat = pattern.matcher(email);
        return mat.matches();
    }

    /**
     * 判断日期格式是否正确
     *
     * @param sDate
     * @return
     */
    public static boolean isValidDate(String sDate) {
        String datePattern1 = "\\d{4}-\\d{2}-\\d{2}";
        String datePattern2 = "^((\\d{2}(([02468][048])|([13579][26]))"
                + "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|"
                + "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"
                + "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?("
                + "(((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?"
                + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
        if ((sDate != null)) {
            Pattern pattern = Pattern.compile(datePattern1);
            Matcher match = pattern.matcher(sDate);
            if (match.matches()) {
                pattern = Pattern.compile(datePattern2);
                match = pattern.matcher(sDate);
                return match.matches();
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 检查对象是否为数字型字符串,包含负数开头的。
     */
    public static boolean isNumeric(Object obj) {
        if (obj == null) {
            return false;
        }
        char[] chars = obj.toString().toCharArray();
        int length = chars.length;
        if (length < 1)
            return false;

        int i = 0;
        if (length > 1 && chars[0] == '-')
            i = 1;

        for (; i < length; i++) {
            if (!Character.isDigit(chars[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查指定的字符串列表是否不为空。
     */
    public static boolean areNotEmpty(String... values) {
        boolean result = true;
        if (values == null || values.length == 0) {
            result = false;
        } else {
            for (String value : values) {
                result &= !isEmpty(value);
            }
        }
        return result;
    }

    /**
     * 把通用字符编码的字符串转化为汉字编码。
     */
    public static String unicodeToChinese(String unicode) {
        StringBuilder out = new StringBuilder();
        if (!isEmpty(unicode)) {
            for (int i = 0; i < unicode.length(); i++) {
                out.append(unicode.charAt(i));
            }
        }
        return out.toString();
    }

    /**
     * 验证姓名是中文
     */
    public static boolean isValidUserName(String name) {
        if (isEmpty(name)) {
            return false;
        } else {

            // ^[_a-zA-Z0-9+\.\u4e00-\u9fa5]{2,6}$
            name = new String(name.getBytes());// 用GBK编码
            // final String pattern_ = "^[_a-zA-Z0-9+\\.\u4e00-\u9fa5]{2,6}$";
            String pattern_ = "^[\u4e00-\u9fa5]{2,6}$";
            Pattern pattern = Pattern.compile(pattern_);
            Matcher mat = pattern.matcher(name);
            return mat.matches();
        }
    }

    /**
     * 验证密码为字母、数字、下划线两者及以上8-20个字符 ^(?![0-9]+$)(?![a-zA-Z]+$)(?![_]+$)\\w{8,20}$
     * (?!^(\\d+|[a-zA-Z]+|[_]+)$)^[\\w]{8,20}$
     */
    public static boolean checkPassword(String password) {
        boolean tag = false;
        if (isEmpty(password)) {
            tag = false;
        } else {
//          String pattern_ = "^(?![0-9]+$)(?![a-zA-Z]+$)(?!^[_]+$)\\w{8,16}$";
//          Pattern pattern = Pattern.compile(pattern_);
//          Matcher mat = pattern.matcher(password);

            String pattern_D = "^[0-9]+\\d";
            String pattern_W = "^[a-zA-Z]+";
            String pattern_Z = "^[~!@#$%^&*?]+";

            Pattern patternD = Pattern.compile(pattern_D);
            Matcher matD = patternD.matcher(password);
            Pattern patternW = Pattern.compile(pattern_W);
            Matcher matW = patternW.matcher(password);
            Pattern patternZ = Pattern.compile(pattern_Z);
            Matcher matZ = patternZ.matcher(password);
            if (matD.matches() || matW.matches() || matZ.matches()) return false;
            return true;
        }
        return tag;
    }

    /**
     * 验证密码为英文加数字
     */
    public static boolean checkPasswordVar(String password) {
        if (isEmpty(password)) return false;
        boolean isDigit = false;
        boolean isLetter = false;
        boolean isCharacter = false;
        for (int i = 0; i < password.length(); i++) {
            if (Character.isDigit(password.charAt(i))) {
                isDigit = true;
            }
            if (Character.isLetter(password.charAt(i))) {
                isLetter = true;
            }
            if (33 <= password.charAt(i) && password.charAt(i) <= 47) {
                isCharacter = true;
            }
            if (58 <= password.charAt(i) && password.charAt(i) <= 64) {
                isCharacter = true;
            }
            if (91 <= password.charAt(i) && password.charAt(i) <= 96) {
                isCharacter = true;
            }
            if (123 <= password.charAt(i) && password.charAt(i) <= 126) {
                isCharacter = true;
            }
        }
        if (!isDigit) {
            return isLetter && isCharacter;
        }
        if (!isLetter) {
            return isDigit && isCharacter;
        }
        if (!isCharacter) {
            return isLetter && isDigit;
        }
        return isDigit && isLetter && isCharacter;
    }

    public static boolean isValidMobile(String mobile) {
        if (StringUtils.isEmpty(mobile))
            return false;
        // Pattern pattern=Pattern.compile("^[13,14,15,18,19]\\d{9}$");
        Pattern pattern = Pattern
                .compile("^((13[0-9])|(14[7])|(15[^4,\\D])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher matcher = pattern.matcher(mobile);
        return matcher.matches();
    }

    public static boolean isValidQQ(String qq) {
        if (StringUtils.isEmpty(qq))
            return false;
        // Pattern pattern=Pattern.compile("^[13,14,15,18,19]\\d{9}$");
        Pattern pattern = Pattern.compile("^[1-9]\\d{3,}$");
        Matcher matcher = pattern.matcher(qq);
        return matcher.matches();
    }

    public static boolean isValidAmount(String amount) {
        if (StringUtils.isEmpty(amount))
            return false;
        Pattern pattern = Pattern
                .compile("^((\\d{1,})|([0-9]+\\.[0-9]{1,2}))$");
        Matcher matcher = pattern.matcher(amount);
        return matcher.matches();
    }

    public static boolean isValidNumber(String url) {
        if (StringUtils.isEmpty(url))
            return false;
        Pattern pattern = Pattern.compile("^\\d{1,}$");
        Matcher matcher = pattern.matcher(url);
        return matcher.matches();
    }

    /**
     * 文本框中过滤特殊字符 [~@#$%^&*_+<>@#¥%] < > % ' " $ = (后台限制的字符)
     */
    public static String StringFilter(String content) {
        if (isEmpty(content)) {
            return "";
        } else {
            String pattern_ = "[~@$%^&*_+<>¥|!!]";

            Pattern pattern = Pattern.compile(pattern_);
            Matcher mat = pattern.matcher(content);
            return mat.replaceAll("").trim();
        }
    }

    /**
     * 验证文本框中是否包含特殊字符 [~@#$%^&*_+<>@#¥%] < > % ' " $ = (后台限制的字符)
     */
    public static boolean hasLawlessStr(String content) {
        if (isEmpty(content)) {
            return false;
        } else {
            String pattern_ = "[@^+_<>%'\"$=*]";
            Pattern pattern = Pattern.compile(pattern_);
            Matcher mat = pattern.matcher(content);
            return mat.find();
        }
    }

    public static String StringSuperFilter(String content) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < content.length(); i++) {
            String text = content.substring(i, i + 1);
            Log.i("text_info", text);

            Pattern p = Pattern.compile("[0-9]*");
            Matcher m = p.matcher(text);
            if (m.matches()) {
                sb.append(text);
            }
            p = Pattern.compile("[a-zA-Z]");
            m = p.matcher(text);
            if (m.matches()) {
                sb.append(text);
            }
            p = Pattern.compile("[\u4e00-\u9fa5]");
            m = p.matcher(text);
            if (m.matches()) {
                sb.append(text);
            }
            p = Pattern.compile("[., -]");
            m = p.matcher(text);
            if (m.matches()) {
                sb.append(text);
            }
        }
        return sb.toString().trim();
    }

    public static boolean StringSuperVerify(String content) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < content.length(); i++) {
            String text = content.substring(i, i + 1);
            Log.i("text_info", text);

            Pattern p = Pattern.compile("[0-9]*");
            Matcher m = p.matcher(text);
            if (m.matches()) {
                sb.append(text);
            }
            p = Pattern.compile("[a-zA-Z]");
            m = p.matcher(text);
            if (m.matches()) {
                sb.append(text);
            }
            p = Pattern.compile("[\u4e00-\u9fa5]");
            m = p.matcher(text);
            if (m.matches()) {
                sb.append(text);
            }
            p = Pattern.compile("[&#~。+,\n *、/.,()()@-《》<>!!“”|¥$??]");
            m = p.matcher(text);
            if (m.matches()) {
                sb.append(text);
            }
        }
        return (sb.toString()).equals(content);
    }

    public static boolean emojiFilter(String content) {
        if (isEmpty(content)) {
            return false;
        } else {
            String reg = "^([a-z]|[A-Z]|[0-9]|[\u2E80-\u9FFF]){3,}|@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?|[wap.]{4}|[www.]{4}|[blog.]{5}|[bbs.]{4}|[.com]{4}|[.cn]{3}|[.net]{4}|[.org]{4}|[http://]{7}|[ftp://]{6}$";
            Pattern pattern = Pattern.compile(reg);
            Matcher mat = pattern.matcher(content);
            return mat.find();
        }
    }


    /**
     * 验证是否境外手机 (^\+?\d{1,3}?(\(\d{2,5})\))(\d{3,15})(-(\d{4,8}))?$
     */
    public static boolean isValidMobileForeign(String content) {
        if (isEmpty(content)) {
            return false;
        } else {
            String pattern_ = "(^\\+?\\d{1,3}?(\\(\\d{2,5})\\))(\\d{3,15})(-(\\d{4,8}))?$";

            Pattern pattern = Pattern.compile(pattern_);
            Matcher mat = pattern.matcher(content);
            return mat.matches();
        }
    }

    /**
     * 隐藏手机号中间四位
     */
    public static String hideMobile(String content) {
        StringBuilder sb = new StringBuilder();
        if (!isEmpty(content) && content.length() > 6) {
            for (int i = 0; i < content.length(); i++) {
                char c = content.charAt(i);
                if (i >= 3 && i <= 6) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 身份证脱敏
     */
    public static String hideIdCard(String content) {
        StringBuilder sb = new StringBuilder();
        if (!isEmpty(content) && content.length() > 16) {
            for (int i = 0; i < content.length(); i++) {
                char c = content.charAt(i);
                if (i >= 14) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 验证港澳台身份证
     */
    public static boolean checkForeignIdCard(String idCard) {
        boolean tag = false;
        if (isEmpty(idCard)) {
            tag = false;
        } else {
            String pattern_ = "^[A-Za-z0-9()]{6,25}$";
            Pattern pattern = Pattern.compile(pattern_);
            Matcher mat = pattern.matcher(idCard);
            return mat.matches();
        }

        return tag;
    }

    /**
     * 验证密身份证
     */
    public static boolean checkIdCard(String idCard) {
        boolean tag = false;
        if (isEmpty(idCard)) {
            tag = false;
        } else {
            String pattern_ = "^[0-9xX]{15,18}$";
            Pattern pattern = Pattern.compile(pattern_);
            Matcher mat = pattern.matcher(idCard);
            return mat.matches();
        }

        return tag;
    }

    /**
     * 将String转换为Long
     *
     * @param str
     * @return
     */
    public static long parserLong(String str) {
        if (str == null || (str = str.trim()).length() <= 0) {
            return 0;
        }
        try {
            return Long.parseLong(str);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 使用java正则表达式去掉多余的.和0
     *
     * @param
     * @return
     */
    public static String subZeroAndDot(String input) {
        if (input.indexOf(".") > 0) {
            input = input.replaceAll("0+?$", "");// 去掉多余的0
            input = input.replaceAll("[.]$", "");// 如最后一位是.则去掉
        }
        return input;
    }

    /**
     * @param @param  accountNo
     * @param @return 设定参数
     * @return String 返回类型
     * @throws
     * @Title: accountNoEncrypt
     * @Description: 账号打码加密
     */
    public static String accountNoEncrypt(String accountNo) {
        if (StringUtils.isEmpty(accountNo))
            return "";

        if (StringUtils.isValidMobile(accountNo))// 手机号打码方式
        {

            accountNo = accountNo.substring(0, 3) + "****"
                    + accountNo.substring(7);
        } else if (StringUtils.isValidEmail(accountNo))// 邮箱打码方式邮箱打码方式
        {
            if (accountNo.lastIndexOf("@") < 4) {
                accountNo = accountNo.charAt(0)
                        + "***"
                        + accountNo.substring(accountNo.indexOf("@"),
                        accountNo.length());
            } else {
                accountNo = accountNo.substring(0, 3)
                        + "***"
                        + accountNo.substring(accountNo.indexOf("@"),
                        accountNo.length());
            }
        } else {
            if (accountNo.length() > 7) {
                accountNo = accountNo.substring(0, 4) + "****"
                        + accountNo.substring(accountNo.length() - 2);
            } else {
                accountNo = accountNo.substring(0, 2) + "***"
                        + accountNo.substring(accountNo.length() - 2);
            }

        }

        return accountNo;
    }

    /**
     * 格式化时间 判断时间是否为“今日”,“昨日”
     *
     * @param time
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String formatDateTime(String time) {
        SimpleDateFormat format = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm");
        if (time == null || "".equals(time)) {
            return "";
        }
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar current = Calendar.getInstance();

        Calendar today = Calendar.getInstance(); // 今天

        today.set(Calendar.YEAR, current.get(Calendar.YEAR));
        today.set(Calendar.MONTH, current.get(Calendar.MONTH));
        today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
        // Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);

        Calendar yesterday = Calendar.getInstance(); // 昨天

        yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
        yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
        yesterday.set(Calendar.DAY_OF_MONTH,
                current.get(Calendar.DAY_OF_MONTH) - 1);
        yesterday.set(Calendar.HOUR_OF_DAY, 0);
        yesterday.set(Calendar.MINUTE, 0);
        yesterday.set(Calendar.SECOND, 0);

        current.setTime(date);

        if (current.after(today)) {
            return "今天 " + time.split(" ")[1];
        } else if (current.before(today) && current.after(yesterday)) {

            return "昨天 " + time.split(" ")[1];
        } else {
            int index = time.indexOf("-") + 1;
            return time.substring(index, time.length());
        }
    }

    /**
     * 将list集合转化成String
     *
     * @param list
     */
    public static String listToString(List<?> list) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            if (i + 1 == list.size()) {
                result += list.get(i).toString();
            } else {
                result += list.get(i).toString() + " ";
            }
        }
        return result;
    }


    /**
     * MD5加密
     *
     * @param str
     * @return
     */
    public static String MD5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = str.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * sha1加密
     * @param str
     * @return
     */
    public static String getSha1(String str) {
        String result = "";
        if (null == str || 0 == str.length()) {
            return result;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            result = new String(buf);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String trim(String string) {
        if (isBlank(string))
            return "";
        return string.replaceAll(" ", "");
    }

    public static boolean equals(String arg0, String arg1) {
        if (arg0 == null && arg1 == null) {
            return true;
        }
        if (arg0 != null && arg0.equals(arg1)) {
            return true;
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值