Android身份证号码正则

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28261207/article/details/82786978

/**
 * 身份证号码验证
 */
public static boolean isIdNO(Context context, String num) {
    // 去掉所有空格
    num = num.replace(" ", "");

    Pattern idNumPattern = Pattern.compile("(\\d{17}[0-9xX])");

    //通过Pattern获得Matcher
    Matcher idNumMatcher = idNumPattern.matcher(num);

    //判断用户输入是否为身份证号
    if (idNumMatcher.matches()) {
        System.out.println("您的出生年月日是:");
        //如果是,定义正则表达式提取出身份证中的出生日期
        Pattern birthDatePattern = Pattern.compile("\\d{6}(\\d{4})(\\d{2})(\\d{2}).*");//身份证上的前6位以及出生年月日

        //通过Pattern获得Matcher
        Matcher birthDateMather = birthDatePattern.matcher(num);

        //通过Matcher获得用户的出生年月日
        if (birthDateMather.find()) {
            String year = birthDateMather.group(1);
            String month = birthDateMather.group(2);
            String date = birthDateMather.group(3);
            if (Integer.parseInt(year) < 1900 // 如果年份是1900年之前
                    || Integer.parseInt(month) > 12 // 月份>12月
                    || Integer.parseInt(date) > 31 // 日期是>31号
                    ) {
                CommonUtil.showToast(context, "身份证号码不正确, 请检查");
                return false;
            }
        }
        return true;
    } else {
        CommonUtil.showToast(context, "请输入正确的身份证号码");
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28261207/article/details/82786978