Apollo
Apollo

Reputation: 9064

Checking phone numbers for equivalence

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

Answers (4)

Joni
Joni

Reputation: 111269

You can't use a single regular expression. To get a canonical representation that can be compared:

  1. Replace an initial + with your international call prefix. In many countries this is 00.
  2. If number doesn't start with the prefix, add the prefix and the country code for your country.
  3. Remove all non-digits.

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

Derek
Derek

Reputation: 8763

This is a pretty neat regex that will replace:

  • any plus sign followed by one or more digits
  • any character that is not a digit or a line break character

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

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

Try this regex

 \(?\d{3}\)?-? *\d{3}-? *-?\d{4}

Or:

^\+?(\d[\d-]+)?(\([\d-.]+\))?[\d-]+\d$

Regex Demo

Upvotes: 0

Ulugbek Umirov
Ulugbek Umirov

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

Related Questions