直接上代码
public static boolean checkIDCard(String str) {
str = trimToEmpty(str).toUpperCase();
if (isEmpty(str)) {
return false;
}
Pattern pattern = Pattern.compile("^\\d{17}(\\d|X)$");
Matcher matcher = pattern.matcher(str);
if (!matcher.matches()) {
return false;
}
int[] cities = {11,12,13,14,15,21,22,23,31,32,33,33,35,36,37,41,42,43,44,45,46,50,50,52,53,54,61,62,63,64,65,71,81,82,91};
str = str.replaceAll("X$", "a");
if (Arrays.binarySearch(cities, Integer.parseInt(str.substring(0, 2))) < 0) {
return false;
}
String sBirthday = str.substring(6, 10) + "-" + Integer.parseInt(str.substring(10, 12)) + "-" + Integer.parseInt(str.substring(12, 14));
Calendar cal = Calendar.getInstance();
try {
cal.setTime(new SimpleDateFormat("yyyy/MM/dd").parse(sBirthday.replaceAll("-", "/")));
} catch (ParseException e) {
e.printStackTrace();
}
if (!sBirthday.equals(cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH))) {
return false;
}
int nSum = 0;
for (int i = 17; i >= 0; i--) {
String c = new Character(str.charAt(17 - i)).toString();
nSum += (Math.pow(2, i) % 11) * Integer.parseInt("a".equals(c) ? "10" : c);
}
if (nSum % 11 != 1) {
return false;
}
return true;
}