Reputation: 9064
What's the best way to check phone numbers in different formats for equivalence?
Different formats:
"(708) 399 7222"
"7083997222"
"708-399-7222"
"708399-7222"
"+1 (708) 399-7222"
"+1 (708)399-7222"
Additional Difficulty: what if the phone number isn't prefaced by the country code?
Upvotes: 1
Views: 101
Reputation: 111269
You can't use a single regular expression. To get a canonical representation that can be compared:
00
.This will be sufficient if you only have to deal with calls made from a single country, for example if you are developing something for internal use at a phone company. If you have to accept a wide range of inputs from different countries with various prefixes I suggest finding a well tested library to do this.
Upvotes: 1
Reputation: 8763
This is a pretty neat regex that will replace:
with a blank string
string text = Regex.Replace( inputString, @"\+\d+|[^0-9\r\n]", "" , RegexOptions.None | RegexOptions.Multiline );
Input:
"(708) 399 7222"
"7083997222"
"708-399-7222"
"708399-7222"
"+1 (708) 399-7222"
"+1 (708)399-7222"
Output:
7083997222
7083997222
7083997222
7083997222
7083997222
7083997222
Upvotes: 0
Reputation: 28403
Try this regex
\(?\d{3}\)?-? *\d{3}-? *-?\d{4}
Or:
^\+?(\d[\d-]+)?(\([\d-.]+\))?[\d-]+\d$
Upvotes: 0
Reputation: 12807
You can implement PhoneEqualityComparer
class. If you deal only with US numbers, the following code will work:
sealed class PhoneEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return string.Equals(NormalizePhone(x), NormalizePhone(y));
}
public int GetHashCode(string obj)
{
return NormalizePhone(obj).GetHashCode();
}
private static string NormalizePhone(string phone)
{
if (phone.StartsWith("+1"))
phone = phone.Substring(2);
return Regex.Replace(phone, @"\D", string.Empty);
}
}
Sample usage:
string[] phones = new[] {
"(708) 399 7222",
"7083997222",
"708-399-7222",
"708399-7222",
"+1 (708) 399-7222",
"+1 (708)399-7222"
};
string[] uniquePhones = phones.Distinct(new PhoneEqualityComparer()).ToArray();
Upvotes: 0