可以使用以下代码来使用正则表达式验证身份证是否合法:

public static boolean isValidIdNumber(String idNumber) {
    String regx = "^\\d{17}[0-9Xx]$";
    Pattern pattern = Pattern.compile(regx);
    Matcher matcher = pattern.matcher(idNumber);
    if (!matcher.matches()) {
        return false;
    }
    // 判断出生日期是否合法
    String birthday = idNumber.substring(6, 14);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    try {
        Date birthDate = sdf.parse(birthday);
        if (!birthday.equals(sdf.format(birthDate))) {
            return false;
        }
    } catch (ParseException e) {
        return false;
    }
    // 判断校验位是否正确
    int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    String[] checkCode = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
    int sum = 0;
    for (int i = 0; i < 17; i++) {
        sum += Integer.parseInt(String.valueOf(idNumber.charAt(i))) * weight[i];
    }
    int mod = sum % 11;
    if (idNumber.charAt(17) != checkCode[mod].charAt(0)) {
        return false;
    }
    return true;
}

这个方法首先使用正则表达式验证身份证号码格式是否正确,然后验证出生日期是否合法,最后验证校验位是否正确。如果以上三个验证都通过,就返回 true


原文地址: https://www.cveoy.top/t/topic/eyao 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录