Java正则校验统一社会信用代码
时间: 2023-07-02 22:11:28 浏览: 237
可以使用以下正则表达式来校验统一社会信用代码:
```java
public static boolean isValidSocialCreditCode(String code) {
String regex = "^[0-9A-Z]{18}$";
if (!code.matches(regex)) {
return false;
}
// 校验第 18 位
int[] weights = { 1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28 };
char[] chars = code.toCharArray();
int sum = 0;
for (int i = 0; i < weights.length; i++) {
char c = chars[i];
int num = 0;
if (c >= '0' && c <= '9') {
num = c - '0';
} else if (c >= 'A' && c <= 'Z') {
num = c - 'A' + 10;
}
sum += num * weights[i];
}
int remainder = sum % 31;
char checkCode = remainder == 0 ? '0' : (char) (31 - remainder + '0');
return checkCode == chars[17];
}
```
这个方法会先校验字符串长度和格式是否正确,然后再根据统一社会信用代码的规则校验第18位校验码是否正确。
阅读全文