Patterns 1 786 1234 5678
suggest changeGiven a normalized phone number like +178612345678 we will get a formatted number with the provided pattern.
private String getFormattedNumber(String phoneNumber) {
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
Phonemetadata.NumberFormat numberFormat = new Phonemetadata.NumberFormat();
numberFormat.pattern = "(\\d{3})(\\d{3})(\\d{4})";
numberFormat.format = "($1) $2-$3";
List<Phonemetadata.NumberFormat> newNumberFormats = new ArrayList<>();
newNumberFormats.add(numberFormat);
Phonenumber.PhoneNumber phoneNumberPN = null;
try {
phoneNumberPN = phoneNumberUtil.parse(phoneNumber, Locale.US.getCountry());
phoneNumber = phoneNumberUtil.formatByPattern(phoneNumberPN, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL, newNumberFormats);
} catch (NumberParseException e) {
e.printStackTrace();
}
return phoneNumber;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents