正则表达式分组捕获身份证生日和性别 和判断是否是身份证
2019-03-06 15:28 会飞的雪鹿 阅读(1812) 评论(0) 编辑 收藏 举报身份证类:有性别和生日
public class IdNoMessage { public DateTime BirthDay { get; set; } public string Sex { get; set; } public bool IsIdNo { get; set; } }
先判断是否是身份证号,有18位和15位身份证 然后提取性别和生日
public IdNoMessage GetIdNoData(string idNo) { var idNoData = new IdNoMessage(); if (string.IsNullOrEmpty(idNo)) { return idNoData; } string regexStr = @"^\d{6}(?<year>[1-2]\d{3})(?<month>(0[1-9]|11|12))(?<day>(0[1-9]|[1-2][0-9]|30|31))\d{2}(?<sex>\d)[\dXx]$|^\d{6}(?<year>\d{2})(?<month>(0[1-9]|11|12))(?<day>(0[1-9]|[1-2][0-9]|30|31))\d{2}(?<sex>\d)$"; Match mat = Regex.Match(idNo, regexStr); if (!mat.Success) { return idNoData; } idNoData.BirthDay = Convert.ToDateTime(mat.Groups["year"].ToString() + "-" + mat.Groups["month"].ToString() + "-" + mat.Groups["day"].ToString()); idNoData.Sex = Convert.ToInt32(mat.Groups["sex"].ToString()) % 2 == 0 ? "F" : "M"; idNoData.IsIdNo = true; return idNoData; }