java用正则表达式判断一个18位身份证号是否有效

2025-04-06 22:28:53
推荐回答(3个)
回答1:

很显然 是你得正则表达式不对啊,正确的18位身份证验证正则为:

String regex = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";		

而且就算正则表达式正确了,你的逻辑判断代码也是有问题,

完成代码如下,请参考:

public class Homework {
public static void main(String[] args) {
String regex = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
System.out.println("请输入18位的身份证号码:");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
if (s.matches(regex)) {
int y1, y2;
String year1 = s.substring(6, 8);
y1 = Integer.parseInt(year1);
String year2 = s.substring(8, 10);
y2 = Integer.parseInt(year2);
if ((y1 == 18 && y2 >= 87 && y2 <= 89)
|| (y1 == 19 && y2 >= 0 && y2 <= 99)
|| (y1 == 20 && y2 <= 17)) {
int m, d;
String month = s.substring(10, 12);
m = Integer.parseInt(month);
String day = s.substring(12, 14);
d = Integer.parseInt(day);
if ((m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12)
&& (d == 31))
System.out.println("有效");
else if ((m == 4 || m == 6 || m == 9 || m == 11) && (d == 30))
System.out.println("有效");
else if (m == 2) {
int y;
String year = s.substring(6, 10);
y = Integer.parseInt(year);
if (((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
&& (d == 29))
System.out.println("有效");
else if (((y % 4 != 0 && y % 100 == 0) || y % 400 != 0)
&& (d == 28))
System.out.println("有效");
else
System.out.println("无效");
return;
} else {
System.out.println("无效");
return;
}
int ss;
String sex = s.substring(16, 17);
ss = Integer.parseInt(sex);
if (ss % 2 == 0)
System.out.println("女性");
else
System.out.println("男性");
} else
System.out.println("无效");
} else
System.out.println("无效");
}
}

回答2:

你这不是身份证的正则,这正则也太随意了,【1-9】没问题,但\d{17}有问题,\d是0-9的数字,但身份证的第7位开始就是出生日期,第7位8位肯定是19或20,接的几位也有限定,但你一个\d完全没有限定值,出生日期0000也可以取到。
/^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/

回答3:

d{16}x" 这里引号前少了个)