C# 記錄一個檢驗身份證號的方法

private string CheckIDCard(string iDCard)
        {
            string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "內蒙古", null, null, null, null, null, "遼寧", "吉林", "黑龍江", null, null, null, null, null, null, null, "上海", "江蘇", "浙江", "安微", "福建", "江西", "山東", null, null, null, "河南", "湖北", "湖南", "廣東", "廣西", "海南", null, null, null, "重慶", "四川", "貴州", "雲南", "西藏", null, null, null, null, null, null, "陝西", "甘肅", "青海", "寧夏", "新疆", null, null, null, null, null, "臺灣", null, null, null, null, null, null, null, null, null, "香港", "澳門", null, null, null, null, null, null, null, null, "國外" };
            double iSum = 0;
            Regex rg = new Regex(@"^\d{17}(\d|X)$"); //45031119750908814X
            Match mc = rg.Match(iDCard);
            if (!mc.Success)
            {
                return "";
            }
            iDCard = iDCard.ToLower();
            iDCard = iDCard.Replace("x", "a");
            if (aCity[int.Parse(iDCard.Substring(0, 2))] == null)
            {
                return "非法地區";
            }
            try
            {
                DateTime.Parse(iDCard.Substring(6, 4) + "-" + iDCard.Substring(10, 2) + "-" + iDCard.Substring(12, 2));
            }
            catch
            {
                return "非法生日";
            }
            for (int i = 17; i >= 0; i--)
            {
                iSum += (Math.Pow(2, i) % 11) * int.Parse(iDCard[17 - i].ToString(), System.Globalization.NumberStyles.HexNumber);
            }
            if (iSum % 11 != 1)
            {
                return ("非法證號");
            }
            return (aCity[int.Parse(iDCard.Substring(0, 2))] + "," + iDCard.Substring(6, 4) + "-" + iDCard.Substring(10, 2) + "-" + iDCard.Substring(12, 2) + "," + (int.Parse(iDCard.Substring(16, 1)) % 2 == 1 ? "男" : "女"));
        }

返回信息比如:河北,1930-10-09,男

記錄在此。

身份證號的正則表達式,跟據自己需求改正

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章