Question

I have a phone number and an ISO country code associated with it. For example, CA for Canada, US for the United States, GB for the UK.

The phone number may contain more than just an area code and your phone's number.

libphonenumber provides functions for determining whether a phone number is valid, given a country code, so I figured there should be a way to normalize it as well.

Does the library provide a way for me to convert this into an object that will properly separate dialing codes, area codes, and the phone number itself? eg: given a UK phone number of the form +44 20 xxxx xxxx, I want it to separate the 44 from the 20 and the xxxx xxxx

I see some normalization methods but they simply remove characters like hyphens, parentheses, and spaces.

Was it helpful?

Solution

It appears that the libphonenumber PhoneNumberUtil format method will do what you want.

String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
    e.printStackTrace();
}

// Produces "044 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, 
    PhoneNumberFormat.NATIONAL));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top