-2

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.

Belhe001
  • 89
  • 9
  • 1
    can you elaborate and explain it with more relevant examples and with regex – Bhargav Modi Dec 23 '16 at 07:30
  • 0446681800 is valid SWITZERLAND number, +134780933xx is US number, number, +9102000000455 is Indian number, so they all should be parsed with their countries. (ie "CH","US","IN" respectively). – Belhe001 Dec 23 '16 at 08:17

1 Answers1

0

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));
}
Ihor Dobrovolskyi
  • 1,241
  • 9
  • 19
  • Switzerland's (CH) calling code is 41, but India's (IN) calling code is 91. if I use phoneUtil.parse("+91-xxx-xxxx-xxx", "CH") will always be false, even for valid numbers. – Belhe001 Dec 23 '16 at 08:00
  • My code works with the examples on your question. Please, edit your question and add the examples you need to work. – Ihor Dobrovolskyi Dec 23 '16 at 08:09
  • 1
    check again, your code will not give proper output for first, second, forth numbers. – Belhe001 Dec 23 '16 at 08:52