C# 提取身份证号
思路:如果号码是18位的,并且符合生日规则,还有前面和后面都不是数字的这种才是身份证号,避免误采
string idCard = " 135412198801245521af888888888888888888,110444199601012145"; idCard = " " + idCard + " "; MatchCollection mcIdCard = Regex.Matches(idCard, @"(\D[1-9]\d{5}[12]\d{3}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])\d{3}[0-9xX]\D)"); foreach (Match match in mcIdCard) { var result = match.Value; result = GetRealIdCardNumber(result); Console.WriteLine(result); } Console.ReadLine();
public static string GetRealIdCardNumber(string input) { var result = string.Empty; if (!string.IsNullOrWhiteSpace(input)) { input = input.Replace(" ", ""); List<string> list = new List<string>(); Regex regex = new Regex(@"([1-9]\d{5}[12]\d{3}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])\d{3}[0-9xX])"); MatchCollection collection = regex.Matches(input); if (collection.Count > 0 && collection[0].Groups.Count > 0) { result = collection[0].Groups[0].Value; } } return result; }