StringUtils 工具类 有正则表达式匹配 合法字符串

import javax.validation.constraints.NotBlank;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
    public static final Pattern VALIDATE_STR_RIGHTFUL = Pattern.compile("^[\\x00-\\x7F\\u4e00-\\u9fff\\uff00-\\uffef]+$");
    public static final Pattern VALIDATE_STR_IS_NUMBER = Pattern.compile("^\\d+$");

    public static String validateStrLengthAndTrimNotBlank(String str, int min, int max, String name) {
        if (str == null) {
            throw new IllegalArgumentException(name + "不能为空");
        }
        String trim = str.trim();
        if (trim.isEmpty()) {
            throw new IllegalArgumentException(name + "不能为空");
        }
        if (trim.length() < min || trim.length() > max) {
            throw new IllegalArgumentException(name + "长度不能超过" + max + "且不能小于" + min);
        }

        if (validateStrRightful(trim)) {
            return trim;
        }

        throw new IllegalArgumentException(name + "包含非法字符[" + str + "],不能包含表情等非法字符!");
    }

    public static String validateStrLengthAndTrimAllowNullOrEmpty(String str, int min, int max, String name) {
        if (str == null) {
            return null;
        }
        String trim = str.trim();

        if (trim.isEmpty()) {
            return trim;
        }

        if (trim.length() < min || trim.length() > max) {
            throw new IllegalArgumentException(name + "长度不能超过" + max + "且不能小于" + min);
        }

        if (validateStrRightful(trim)) {
            return trim;
        }

        throw new IllegalArgumentException(name + "包含非法字符[" + str + "],不能包含表情等非法字符!");
    }

    public static boolean validateStrContainSpace(String str) {
        return str.contains(" ");
    }

    public static boolean validateStrIsNumber(String str) {
        return VALIDATE_STR_IS_NUMBER.matcher(str).matches();
    }

    /**
     * 校验字符合法性 非空的
     */
    public static boolean validateStrRightful(@NotBlank String str) {
        return VALIDATE_STR_RIGHTFUL.matcher(str).matches();
    }

    public static String replaceAllStrMatch(String str, String replaceAll, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.replaceAll(replaceAll);
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值