Java 检测有没有特殊字符 UTF8mb4
public static boolean isContainSpecialChar(String str) {
if(StringUtils.isEmpty(str)){
return false;
}
try {
byte[] bytes = str.getBytes("UTF-8");
for (int i = 0; i < bytes.length; i++) {
if(isStartWithOver3Byte(bytes[i])){
return true;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断字节范围是否在四,五,六范围内
*
* 1字节 0xxxxxxx
* 2字节 110xxxxx 10xxxxxx
* 3字节 1110xxxx 10xxxxxx 10xxxxxx
* 4字节 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
* 5字节 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
* 6字节 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
* @param b
* @return
*/
public static boolean isStartWithOver3Byte(byte b) {
int unsignByte = Byte.toUnsignedInt(b);
return (0xf0 <= unsignByte && unsignByte <= 0xf7) ||//4字节开头
(0xf8 <= unsignByte && unsignByte <= 0xfb) ||//5字节开头
(0xfc <= unsignByte && unsignByte <= 0xfd);//6字节开头
}
public static void main(String[] args){
String str="€😘jekj,fj€dks@";//笑脸4个字节
String str2="⏰kjsfjfjfj";//闹钟三个字节
String str3="€";//三个字节
System.out.println(isContainSpecialChar(str));
System.out.println(isContainSpecialChar(str2));
System.out.println(isContainSpecialChar(str3));
}