当前位置:网站首页>C#入门-利用正则表达式校验身份证号
C#入门-利用正则表达式校验身份证号
2022-04-21 09:57:00 【学到老才能活到老】
题目:对输入框中输入的身份证是否合法进行验证:
1)使用正则表达式对格式进行验证(共18位,前17位为数字,最后1位是数字或字母,其中年月日部分也可以进行验证;
2)对身份证的最后一位的有效性进行验证。
最后一位校验规则:

代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApp17
{
class Program
{
static void Parseid(string id)
{
string pattern = @"^\d{17}(?:\d|X)$";
string birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
DateTime time = new DateTime();
int[] arr_weight = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 加权数组
string[] id_last = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }; // 校验数组
int sum = 0;
for (int i = 0; i < 17; i++)
{
sum += arr_weight[i] * int.Parse(id[i].ToString());
}
int result = sum % 11; // 实际校验位的值
if (Regex.IsMatch(id, pattern)) // 18位格式检查
{
if(DateTime.TryParse(birth, out time)) // 出生日期检查
{
if (id_last[result] == id[17].ToString()) // 校验位检查
{
Console.WriteLine("身份证号格式正确!");
}
else
{
Console.WriteLine("最后一位校验错误!");
}
}
else
{
Console.WriteLine("出生日期验证失败!");
}
}
else
{
Console.WriteLine("身份证号格式错误!");
}
}
static void Main(string[] args)
{
string id;
id = Console.ReadLine();
Parseid(id);
Console.Read();
}
}
}
运行结果我就不放了,拿你自己身份证号验证一下吧。
版权声明
本文为[学到老才能活到老]所创,转载请带上原文链接,感谢
https://blog.csdn.net/MARS_098/article/details/105632343
边栏推荐
猜你喜欢

Transaction isolation level and mvcc

刷题记录(牛客MySQL)
![Kali:sqlmap :[10:39:37] [CRITICAL] unable to connect to the target URL](/img/bf/123e6f5eadb8d502e135a7cff9b120.png)
Kali:sqlmap :[10:39:37] [CRITICAL] unable to connect to the target URL

The display problem of gltf model with transparent map

控制另一个程序的启动、隐藏、显示、关闭

比 Navicat 还要好用、功能更强大的工具!

【并发编程045】什么是伪共享内存顺序冲突?如何避免?

外显子bed文件获取

【并发编程043】CAS存在的问题,ABA问题,如何解决的?

一文读懂Seek Tiger推出创世节点的意义
随机推荐
About incorrect deletion of operations in notes
常用文本处理命令
[Yugong series] wechat applet - API related function case of map use in April 2022
SQL:树形三层职业分类表的SQL文件
【无标题】
Sixtool, which is launched in the whole network, is a multi-functional and multi-in-one generation hanging assistant. It supports BiliBili, movement steps and other functions. The operating version ca
CANoe:Vector Tool Platform是什么
利用pycharm在Pyside2中加载qrc资源文件
ArrayList集合
TensorflowEager的查看关闭开启
【并发编程044】CAS循环时间太长,会有什么问题?
[notes] Launch file syntax record
利用已有的标签文件生成训练集和验证集(YOLO)
2022年A特种设备相关管理(电梯)考试试题模拟考试平台操作
Operation of simulation test platform for test questions of refrigeration and air conditioning equipment operation test in 2022
Various methods provided by C string
Promise处理复杂异步
当uniapp遇上滚动穿透,巧妙的解决方式~
ant a-table 表格数据同步
每日一题(2022-04-20)——文件的最长绝对路径