python正则表达式身份证号码
时间: 2023-11-20 17:56:55 浏览: 73
以下是Python中使用正则表达式验证身份证号码的例子:
```python
import re
def is_valid_id_number(id_number):
# 15位或18位数字,最后一位可以是字母X
pattern = r'^\d{15}|\d{18}|(\d{17}[xX])$'
if re.match(pattern, id_number):
return True
else:
return False
# 测试
id_number = '11010119900307771X'
if is_valid_id_number(id_number):
print('身份证号码合法')
else:
print('身份证号码不合法')
```
相关问题
python正则表达式匹配身份证
身份证号码是一个固定格式的字符串,可以使用正则表达式进行匹配。以下是一个简单的Python正则表达式匹配身份证号码的例子:
```python
import re
id_number = "110101199003076119" # 身份证号码
pattern = re.compile(r'^[1-9]\d{5}(19|20)\d{2}(0\d|1[0-2])([0-2]\d|3[0-1])\d{3}[\dX]$')
# 匹配身份证号码的正则表达式
result = pattern.match(id_number)
if result:
print("匹配成功")
else:
print("匹配失败")
```
解释一下正则表达式的含义:
- `^` 表示匹配字符串的开头;
- `[1-9]` 表示第一位必须是1-9中的一个数字;
- `\d{5}` 表示接下来的5位必须是数字;
- `(19|20)` 表示接下来的两位必须是19或20;
- `\d{2}` 表示接下来的两位必须是数字;
- `(0\d|1[0-2])` 表示接下来的两位必须是01-12中的一个数字;
- `([0-2]\d|3[0-1])` 表示接下来的两位必须是01-31中的一个数字;
- `\d{3}` 表示接下来的3位必须是数字;
- `[\dX]` 表示最后一位必须是数字或大写字母X;
- `$` 表示匹配字符串的结尾。
使用正则表达式进行身份证号码的匹配可以有效地提高准确率和效率。
python正则表达式校验身份证
以下是使用Python正则表达式校验身份证的方法:
```python
import re
def check_id_card(id_card):
# 身份证正则表达式
pattern = re.compile(r'^[1-9]\d{5}(19\d{2}|20[01]\d)(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$')
# 匹配身份证号码
match = pattern.match(id_card)
if match:
# 校验码校验
id_card = list(id_card)
id_card_sum = 0
for i in range(17):
id_card[i] = int(id_card[i])
id_card_sum += id_card[i] * (2 ** (17 - i))
id_card_check = (12 - id_card_sum % 11) % 11
if id_card_check == 10:
id_card_check = 'X'
if str(id_card_check) == id_card[-1]:
return True
else:
return False
else:
return False
```
使用方法:
```python
id_card = '110101199003074518'
if check_id_card(id_card):
print('身份证号码校验通过')
else:
print('身份证号码校验不通过')
```
输出结果:
```
身份证号码校验通过
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)