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);
}
}
StringUtils 工具类 有正则表达式匹配 合法字符串
最新推荐文章于 2025-07-30 20:46:17 发布