开箱即用,无副作用
/**
* 身份证正则表达式
* @author LIFULIN
* @className CheckIdCardRuleUtil
* @description TODO
* @date 2020/8/31-15:39
*/
public class CheckIdCardRuleUtil {
/**
* 加权因子
*/
private static final int[] WEIGHT = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1};
/**
* 校验码
*/
private static final int[] CHECK_DIGIT = new int[]{1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2};
/**
* 不可被实例化
*/
public CheckIdCardRuleUtil() {
}
/**
* 校验身份证
* @param idCard 身份证
* @return boolean
*/
public boolean verify(String idCard) {
if (idCard.length() == 15) {
idCard = this.checkOneNdGenerationIdCard(idCard);
}
if (idCard.length() != 18) {
return false;
}
String checkDigit = idCard.substring(17, 18);
return checkDigit.equals(this.checkTowNdGenerationIdCard(idCard));
}
/**
* 二代身份证验证
*
* @param towNdIdCard 二代身份证id
* @return
*/
private String checkTowNdGenerationIdCard(String towNdIdCard) {
int remaining = 0;
if (towNdIdCard.length() == 18) {
towNdIdCard = towNdIdCard.substring(0, 17);
}
if (towNdIdCard.length() == 17) {
int sum = 0;
int[] a = new int[17];
for (int i = 0; i < 17; i++) {
String k = towNdIdCard.substring(i, i + 1);
a[i] = Integer.parseInt(k);
}
for (int i = 0; i < 17; i++) {
sum = sum + WEIGHT[i] * a[i];
}
remaining = sum % 11;
}
return remaining == 2 ? "X" : String.valueOf(CHECK_DIGIT[remaining]);
}
/**
* 判断一代身份证
*
* @param oneNdIdCard
* @return
*/
private String checkOneNdGenerationIdCard(String oneNdIdCard) {
String eighteenCardId = oneNdIdCard.substring(0, 6);
eighteenCardId = eighteenCardId + "19";
eighteenCardId = eighteenCardId + oneNdIdCard.substring(6, 15);
eighteenCardId = eighteenCardId + this.checkTowNdGenerationIdCard(eighteenCardId);
return eighteenCardId;
}
}