Java检测字符串有没有特殊字符

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));
    }
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值