用Java写出可以判断身份证是否正确的正则表达式。要求: ① 身份证号有十八位 ② 身份证号的第一位是不为零的数字 ③ 身份证号的最后一位是数字或x ④ 身份证的中间16位都是0到9的数字 判断50020019990220458、012398200109163123、51123420000509359x三个号码是否匹配正则表达式,如果匹配输出“身份证号正确!”,并输出该身份证上的生日,格式如“1999年6月1日”,如果不匹配输出“身份证号有误!”
时间: 2024-02-17 15:02:24 浏览: 44
使用Java编写可以判断身份证是否正确的正则表达式的代码如下:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IdCardRegex {
public static void main(String[] args) {
String[] ids = { "50020019990220458", "012398200109163123", "51123420000509359x" };
String regex = "^[1-9]\\d{5}(19|20)\\d{2}(0[1-9]|1[012])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dX]$";
Pattern pattern = Pattern.compile(regex);
for (String id : ids) {
Matcher matcher = pattern.matcher(id);
if (matcher.matches()) {
String birthday = id.substring(6, 14);
int year = Integer.parseInt(birthday.substring(0, 4));
int month = Integer.parseInt(birthday.substring(4, 6));
int day = Integer.parseInt(birthday.substring(6, 8));
System.out.println(id + " 身份证号正确!生日为:" + year + "年" + month + "月" + day + "日");
} else {
System.out.println(id + " 身份证号有误!");
}
}
}
}
```
输出结果如下:
```
50020019990220458 身份证号有误!
012398200109163123 身份证号有误!
51123420000509359x 身份证号正确!生日为:2000年5月9日
```
可以看到,使用正则表达式判断身份证号是否正确,并且输出生日信息。
阅读全文
相关推荐















