Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use formatByPattern (libphonenumber.jar)?

I'm using Google's libphonenumber library to validate and format a phone number in a Java application.

Below is the code I'm using:

String phoneNumberE164Format = "3365440901";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, "US");
phoneNumberE164Format = phoneUtil.formatByPattern(phoneNumberProto, 
                           PhoneNumberFormat.INTERNATIONAL, ******);

The method signature is as such:

public java.lang.String formatByPattern(PhoneNumber number,
                                        PhoneNumberUtil.PhoneNumberFormat numberFormat,
                                        java.util.List<NumberFormat> userDefinedFormats);

Now I don't understand what should be entered for the third parameter.

I would want the format to be like below:

+1.410.218.9999 OR
+1-210-125-9999
like image 203
Rakesh Garia Avatar asked Apr 07 '26 10:04

Rakesh Garia


1 Answers

Milind Gokhale's comment above gave me a good lead to finding the solution.

The code below formats any valid phone number to the format specified in this question:

NumberFormat newNumFormat = new NumberFormat();
newNumFormat.pattern = "(\\d{3})(\\d{3})(\\d{4})";
newNumFormat.format = "$1-$2-$3";

List<NumberFormat> newNumberFormats = new ArrayList<NumberFormat>();
newNumberFormats.add(newNumFormat);

String formatted = phoneUtil.format(phoneNumberProto, PhoneNumberFormat.RFC3966).substring(4);
like image 137
Rakesh Garia Avatar answered Apr 08 '26 23:04

Rakesh Garia