Android身份证号码正则

本文详细介绍了如何使用正则表达式验证身份证号码的有效性,并从中提取出生日期信息,确保其符合日期规范。通过实例展示了身份证号码的匹配和日期合法性检查过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/**
 * 身份证号码验证
 */
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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值