无论是日常生活还工作需要,我们会经常使用到身份证,身份证可以用于证明用户身份的证件,那么,我们如何通过正则表达式来验证某个身份证是否合法呢?下面,济南网站建设小编就来为大家介绍在c#编程语言中通过正则表达式验证身份证号码是否合法具体实现方法,有需要的朋友可以过来关注一下
关键代码:
using System;
using System.Text.RegularExpressions;
public class IDValidator
{
private static readonly string Pattern = @"^\d{17}[\dXx]$|^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9Xx])$";
public static bool ValidateID(string id)
{
if (id == null) return false;
// 使用正则表达式进行初步验证
var match = Regex.Match(id, Pattern);
// 如果匹配失败,直接返回false
if (!match.Success) return false;
// 进一步验证18位身份证号码的校验码
if (id.Length == 18)
{
char[] weights = new char[] { '7', '9', '1', '0', '3', '5', '8', '4', '2', '1', '6', '7', '9', '1', '0', '3', '5' };
string[] validationCodes = "10X98765432".ToCharArray().Select(c => c.ToString()).ToArray();
int sum = 0;
for (int i = 0; i < 17; i++)
{
sum += (id[i] - '0') * (weights[i] - '0');
}
string checkCode = validationCodes[sum % 11];
if (checkCode.ToUpper() != id[17].ToString().ToUpper())
{
return false;
}
}
return true;
}
}
评论