使用正则表达式匹配身份证号
时间: 2023-10-02 14:08:32 浏览: 98
可以使用以下正则表达式验证身份证号格式是否合法:
```python
import re
id_card = input("请输入身份证号:")
# 正则表达式
pattern = r'^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}[0-9Xx]$'
if re.match(pattern, id_card):
print("身份证号格式合法!")
else:
print("身份证号格式不合法!")
```
其中,正则表达式的含义如下:
- `^` 表示匹配字符串的开头;
- `[1-9]` 表示第一位必须是非零数字;
- `\d{5}` 表示接下来的 5 位可以是任意数字;
- `(19|20)\d{2}` 表示年份必须是 19 或 20 开头的 4 位数字;
- `(0[1-9]|1[0-2])` 表示月份必须是 01 到 12 之间的 2 位数字;
- `(0[1-9]|[1-2]\d|3[0-1])` 表示日期必须是 01 到 31 之间的 2 位数字;
- `\d{3}` 表示接下来的 3 位可以是任意数字;
- `[0-9Xx]` 表示最后一位可以是数字或者大写字母 X 或小写字母 x;
- `$` 表示匹配字符串的结尾。
如果输入的身份证号符合以上规则,则输出“身份证号格式合法!”;否则输出“身份证号格式不合法!”
相关问题
js正则表达式匹配身份证号码
可以使用以下正则表达式匹配身份证号码:
```javascript
/^\d{17}[\dXx]$/
```
其中,`\d` 表示数字,`{17}` 表示前面的数字必须出现 17 次,`[\dXx]` 表示最后一位可以是数字或者大写字母 X 或小写字母 x。
示例代码:
```javascript
const idCardRegex = /^\d{17}[\dXx]$/;
const idCardNumber = '11010119900307771X';
if (idCardRegex.test(idCardNumber)) {
console.log('身份证号码格式正确');
} else {
console.log('身份证号码格式错误');
}
```
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;
- `$` 表示匹配字符串的结尾。
使用正则表达式进行身份证号码的匹配可以有效地提高准确率和效率。
阅读全文
相关推荐
![mhtml](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)