实现一个身份证号码验证程序
时间: 2024-12-22 16:18:52 浏览: 29
实现一个身份证号码验证程序通常涉及两个步骤:检查身份证号码的格式是否正确,并验证其校验码是否有效。中国身份证号码有18位数字,分为三部分:前6位代表地区编码,接下来8位是出生日期码,最后4位是顺序码加校验码。
以下是简单的Python示例,使用正则表达式和数学逻辑:
```python
import re
def validate_id(id_number):
# 正则表达式匹配中国的身份证号码格式
pattern = r'^\d{15}(?:\d{2}[Xx])?$'
if not re.match(pattern, id_number):
return False # 格式错误
# 切分身份证号码
area_code, birth_date, check_digit = id_number[:-2], id_number[6:-4], id_number[-2:]
# 验证出生日期码
year, month, day = map(int, birth_date.split(''))
if (year < 1900 or year > 2022) or (month < 1 or month > 12) or (day < 1 or day > 31):
return False
# 计算校验码
weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
sum_val = sum(a * b for a, b in zip(weights, id_number[:-1].split('')))
# 累加结果根据奇偶调整,加权相乘后取余数
remainder = sum_val % 11 if sum_val % 11 <= 1 else 11 - sum_val % 11
return remainder == int(check_digit) and check_digit.lower() in ['x', 'x']
# 示例
id_to_validate = "123456789012345678"
if validate_id(id_to_validate):
print("身份证号码有效")
else:
print("身份证号码无效")
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)