如何在C#中比较两个字符串的最后10位(英国手机号验证)
C#中比较手机号最后10位判断匹配
给定以下两个字符串:
string phoneNumber1 = "01234567899"; string PhoneNumber2 = "+441234567899";上述两个字符串为同一英国手机号的两种不同格式,请问如何在C#中仅比较这两个字符串的最后10位,以判断它们是否匹配?
解决方案
直接截取最后10位对比
先处理空值或长度不足的边界情况,再截取字符串末尾10位进行比较:string phone1 = "01234567899"; string phone2 = "+441234567899"; if (string.IsNullOrEmpty(phone1) || string.IsNullOrEmpty(phone2)) { // 业务逻辑:空手机号视为不匹配或抛出异常 Console.WriteLine("手机号不能为空"); return; } string last10Phone1 = phone1.Length >= 10 ? phone1.Substring(phone1.Length - 10) : phone1; string last10Phone2 = phone2.Length >= 10 ? phone2.Substring(phone2.Length - 10) : phone2; bool isMatch = last10Phone1.Equals(last10Phone2); Console.WriteLine(isMatch); // 输出 True先清理非数字字符再截取
如果手机号可能包含空格、括号等干扰符号,先过滤掉所有非数字字符,再取最后10位对比:using System.Text.RegularExpressions; string phone1 = "01234567899"; string phone2 = "+441234567899"; // 移除所有非数字字符 string cleanPhone1 = Regex.Replace(phone1, @"[^\d]", ""); string cleanPhone2 = Regex.Replace(phone2, @"[^\d]", ""); string last10Phone1 = cleanPhone1.Length >= 10 ? cleanPhone1.Substring(cleanPhone1.Length - 10) : cleanPhone1; string last10Phone2 = cleanPhone2.Length >= 10 ? cleanPhone2.Substring(cleanPhone2.Length - 10) : cleanPhone2; bool isMatch = last10Phone1.Equals(last10Phone2); Console.WriteLine(isMatch); // 输出 True
内容的提问来源于stack exchange,提问作者EKD
相关产品推荐
相关产品推荐

