How to match phone numbers from user's contact list if numbers are in different format?

Viewed 123

I have a question about how to match phone numbers from user's contact list with phone numbers I have on remote database. Flow goes like this:

  1. User registers on my app with his phone number (so does any other user)
  2. App ask for contact permission
  3. App sends contacts (phone numbers) to server to match against other registered numbers

The problem I have is that users register their phone number in format: +1XXXYYY. For example person A registers with number +1222333. It might happen that person B has person A in his contact list as 0222333, how should I match that number? I can't know if prefix is "+1" or some other number.

1 Answers

I would like to recommend the libphonenumber library: https://github.com/google/libphonenumber It can parse numbers and then output then to a standardized format. The official library has support for Java, C++ and JavaScript but there are also ports to other languages (see the bottom of the Github page)

Here is a quick example on how to format a national number as an international one in java

public static String getInternationalNumber(String localNumber, String regionCode) {
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber phoneNumber;
    try {
        phoneNumber = phoneUtil.parse(localNumber, regionCode);
    }
    catch (NumberParseException e) {
        return null;
    }

    return (phoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL));
}

You can probably assume that the numbers in the user's contact list have the same country code as the user.

To find which country code your user's phone number has you can do something like this (assuming it is an international number)

public static String getRegionCode(String phone) {
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber phoneNumber;
    try {
        phoneNumber = phoneUtil.parse(phone, "");
    }
    catch (NumberParseException e) {
        return null;
    }
    return phoneUtil.getRegionCodeForNumber(phoneNumber);
}
Related