Parsing Phone Numbers to their parts

11,911

Solution 1

The libphonenumber library will parse a number and validate that it matches a known pattern for domestic and international numbers. It will tell you the country code and the correct dialing pattern domestically or internationally for any given number.

It will not parse it into constituent parts beyond that. No area code, prefix, number, extension parsing.

It's open source so if you need to do this it might be a good starting place, but I'm sure it'll be a huge undertaking.

Solution 2

Patrick Mezard has kindly ported the library to C#:

https://bitbucket.org/pmezard/libphonenumber-csharp/wiki/Home

For usage, you can look at the official web site:

http://code.google.com/p/libphonenumber/

The Java code can be directly translated to C#. For example:

Java

String swissNumberStr = "044 668 18 00"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}

C#

String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance();
try
{
    PhoneNumber swissNumberProto = phoneUtil.Parse(swissNumberStr, "CH");
    Console.WriteLine(swissNumberProto.CountryCode);
}
catch (NumberParseException e)
{
    Console.WriteLine("NumberParseException was thrown: " + e.ToString());
}

Good luck.

Update:

More examples: http://code.google.com/p/libphonenumber/source/browse/#svn/trunk/java/libphonenumber/test/com/google/i18n/phonenumbers

If you don't see what you need, then I guess you can implement it yourself.

Share:
11,911

Related videos on Youtube

MB34
Author by

MB34

Updated on September 19, 2022

Comments

  • MB34
    MB34 over 1 year

    I know about the C# port of the Google libphonenumber Parsing Library: http://code.google.com/p/libphonenumber/

    What I need is to take a phone number string and break it up into the corresponding pieces, Country Code, Area Code, Prefix, Number, and Extension.

    Can this library be used to do that? If so, can someone post a simple test in C# to do that? I don't see how to do it in the docs.

    BTW, they can be domestic or international.

  • JamesUsedHarden
    JamesUsedHarden over 11 years
    @MB34, nice library, but it separates numbers into parts, it doesn't label the parts country code, prefix, area code, etc. One really neat thing that library does is handle letters properly, like 1-800-MY-PHONE.