How to get a valid phone number from text document using libphonenumber?

569 views Asked by At

libphonenumber requires a phone number and a country name as a parameter to verify a phone number.

        PhoneNumber numberProto = phoneUtil.parse("044 668 18 00", "CH");
        System.out.println(numberProto);
        System.out.println("is valid: "+phoneUtil.isValidNumber(numberProto));

I can find phone numbers from a text document using regex, but not country name associated with that particular phone number.

Please, suggest me a way to find valid phone numbers from text.

Example input:

..some text.. first number +13478093374 ..some text..
some new text.. second number.. +91 774-5001-827 ..some text.
some new text.. third number.. 044 668 18 00 ..some text.
some new text.. forth number.. 020-2689-0455 ..some text.

so the respective output should be,

phoneUtil.parse("044 668 18 00", "CH") //valid
phoneUtil.parse("+91 774-5001-827", "IN") //valid
phoneUtil.parse("+13478093374", "US") //valid
phoneUtil.parse("020-2689-0455", "IN") //valid

Please suggest a algorithm to add country parameter.

1

There are 1 answers

3
Ihor Dobrovolskyi On

You can use the regex like this:

"(\d\d\d)-(\d\d\d\d)-(\d\d\d)\s"

Then use the code like this:

Pattern pattern = Pattern.compile("(\\d\\d\\d)-(\\d\\d\\d\\d)-(\\d\\d\\d)\\s");
String phoneNumber = "";
String text = "..some text.. valid number 774-0000-827 ..some text..";
Matcher matcher = pattern.matcher(text);

if (matcher.find())
{
    phoneNumber += matcher.group(1) + " ";
    phoneNumber += matcher.group(2) + " ";
    phoneNumber += matcher.group(3) + " ";

    PhoneNumber numberProto = phoneUtil.parse(phoneNumber, "CH");
    System.out.println(numberProto);
    System.out.println("is valid: "+ phoneUtil.isValidNumber(numberProto));
}