Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.

What is it?

Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers. The Java version is optimized for running on smartphones, and is used by the Android framework since 4.0 (Ice Cream Sandwich).

Quick links

Highlights of functionality

  • Parsing, formatting, and validating phone numbers for all countries/regions of the world.
  • getNumberType - gets the type of the number based on the number itself; able to distinguish Fixed-line, Mobile, Toll-free, Premium Rate, Shared Cost, VoIP, Personal Numbers, UAN, Pager, and Voicemail (whenever feasible).
  • isNumberMatch - gets a confidence level on whether two numbers could be the same.
  • getExampleNumber and getExampleNumberForType - provide valid example numbers for all countries/regions, with the option of specifying which type of example phone number is needed.
  • isPossibleNumber - quickly guesses whether a number is a possible phone number by using only the length information, much faster than a full validation.
  • isValidNumber - full validation of a phone number for a region using length and prefix information.
  • AsYouTypeFormatter - formats phone numbers on-the-fly when users enter each digit.
  • findNumbers - finds numbers in text.
  • PhoneNumberOfflineGeocoder - provides geographical information related to a phone number.
  • PhoneNumberToCarrierMapper - provides carrier information related to a phone number.
  • PhoneNumberToTimeZonesMapper - provides timezone information related to a phone number.

Demo

Java

The Java demo is updated with a slight delay after the GitHub release.

Last demo update: v8.12.39.

If this number is lower than the latest release's version number, we are between releases and the demo may be at either version.

JavaScript

The JavaScript demo may be run at various tags; this link will take you to master.

Java code

To include the Java code in your application, either integrate with Maven (see wiki) or download the latest jars from the Maven repository.

Javadoc

Javadoc is automatically updated to reflect the latest release at https://javadoc.io/doc/com.googlecode.libphonenumber/libphonenumber/.

Versioning and Announcements

We generally choose the release number following these guidelines.

If any of the changes pushed to master since the last release are incompatible with the intent / specification of an existing libphonenumber API or may cause libphonenumber (Java, C++, or JS) clients to have to change their code to keep building, we publish a major release. For example, if the last release were 7.7.3, the new one would be 8.0.0.

If any of those changes enable clients to update their code to take advantage of new functionality, and if clients would have to roll-back these changes in the event that the release was marked as "bad", we publish a minor release. For example, we'd go from 7.7.3 to 7.8.0.

Otherwise, including when a release contains only metadata changes, we publish a sub-minor release, e.g. 7.7.3 to 7.7.4.

Sometimes we make internal changes to the code or metadata that, while not affecting compatibility for clients, could affect compatibility for porters of the library. For such changes we make announcements to libphonenumber-discuss. Such changes are not reflected in the version number, and we would publish a sub-minor release if there were no other changes.

Want to get notified of new releases? During most of the year, excepting holidays and extenuating circumstances, we release fortnightly. We update release tags and document detailed release notes. We also send an announcement to libphonenumber-discuss for every release.

Quick Examples

Let's say you have a string representing a phone number from Switzerland. This is how you parse/normalize it into a PhoneNumber object:

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());
}

At this point, swissNumberProto contains:

{
  "country_code": 41,
  "national_number": 446681800
}

PhoneNumber is a class that was originally auto-generated from phonenumber.proto with necessary modifications for efficiency. For details on the meaning of each field, refer to resources/phonenumber.proto.

Now let us validate whether the number is valid:

boolean isValid = phoneUtil.isValidNumber(swissNumberProto); // returns true

There are a few formats supported by the formatting method, as illustrated below:

// Produces "+41 44 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));
// Produces "044 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));
// Produces "+41446681800"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164));

You could also choose to format the number in the way it is dialed from another country:

// Produces "011 41 44 668 1800", the number when it is dialed in the United States.
System.out.println(phoneUtil.formatOutOfCountryCallingNumber(swissNumberProto, "US"));

Formatting Phone Numbers 'as you type'

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("US");
System.out.println(formatter.inputDigit('6'));  // Outputs "6"
...  // Input more digits
System.out.println(formatter.inputDigit('3'));  // Now outputs "650 253"

Geocoding Phone Numbers

PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();
// Outputs "Zurich"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.ENGLISH));
// Outputs "Zürich"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.GERMAN));
// Outputs "Zurigo"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.ITALIAN));

Mapping Phone Numbers to original carriers

Caveat: We do not provide data about the current carrier of a phone number, only the original carrier who is assigned the corresponding range. Read about number portability.

PhoneNumber swissMobileNumber =
    new PhoneNumber().setCountryCode(41).setNationalNumber(798765432L);
PhoneNumberToCarrierMapper carrierMapper = PhoneNumberToCarrierMapper.getInstance();
// Outputs "Swisscom"
System.out.println(carrierMapper.getNameForNumber(swissMobileNumber, Locale.ENGLISH));

More examples on how to use the library can be found in the unit tests.

Third-party Ports

Several third-party ports of the phone number library are known to us. We share them here in case they're useful for developers.

However, we emphasize that these ports are by developers outside the libphonenumber project. We do not evaluate their quality or influence their maintenance processes.

Alternatives to our own versions:

  • Android-optimized: Our Java version loads the metadata from Class#getResourcesAsStream and asks that Android apps follow the Android loading best practices of repackaging the metadata and loading from AssetManager#open() themselves (FAQ). If you don't want to do this, check out the port at https://github.com/MichaelRocks/libphonenumber-android, which does repackage the metadata and use AssetManager#open(), and may be depended on without needing those specific loading optimizations from clients. You should also check out the port at https://github.com/lionscribe/libphonenumber-android which also supports geocoding, and only requires a one line code change.
  • Javascript: If you don't want to use our version, which depends on Closure, there are several other options, including https://github.com/catamphetamine/libphonenumber-js - a stripped-down rewrite, about 110 KB in size - and https://github.com/seegno/google-libphonenumber - a browserify-compatible wrapper around the original unmodified library installable via npm, which packs the Google Closure library, about 420 KB in size.
Owner
Google
Google ❤️ Open Source
Google
Comments
  • support of singleton and lock for win32 and c++ 11

    support of singleton and lock for win32 and c++ 11

    The pull request #2371 added support for lock with c++ 11, but not Singleton.

    This PR provide support of both singleton and lock for both C++11 and Windows native Win32 API (like posix does).

  • Add new c++ build options for use protobuf-lite

    Add new c++ build options for use protobuf-lite

    Original commit from Timur Kristóf (#2363)

    Add ability for the C++ library to link against protobuf-lite. .

    USE_PROTOBUF_LITE - When this is set to ON then it links against protobuf-lite instead of the full version of protobuf. As far as I could see the metadata has option optimize_for = LITE_RUNTIME; so it should be safe to use the lite version. This is useful when you want to save some disk space. The default is OFF.

    see https://github.com/google/libphonenumber/pull/2363 for original PR

    discussion about protobuf vs protobif lite : https://stackoverflow.com/questions/6405767/protocol-buffer-lite-versus-regular-protocol-buffer

    @Venemo @penmetsaa

  • Move common metadata loading logic into MetadataManager, removing synchronization everywhere

    Move common metadata loading logic into MetadataManager, removing synchronization everywhere

    ** Note for reviewers, do not copy into final commit ** cl/137686080 b/30158468 b/30807096

    pkgdiff: ~keghani/GitHub_diffs/f51e431/pkgdiff_reports/cpp-build/1.0-SNAPSHOT-jar-with-dependencies_to_1.0-SNAPSHOT-jar-with-dependencies/changes_report.html ~keghani/GitHub_diffs/f51e431/pkgdiff_reports/java-build/1.0-SNAPSHOT-jar-with-dependencies_to_1.0-SNAPSHOT-jar-with-dependencies/changes_report.html

    The jars picked up some .class changes since https://github.com/googlei18n/libphonenumber/pull/1432.


    This change is Reviewable

  • Update Brazil carrier selection codes used for dialling long-distance (BR, +55)

    Update Brazil carrier selection codes used for dialling long-distance (BR, +55)

    • adjust for carrier codes (CSP in portuguese), based on anatel site http://sistemas.anatel.gov.br/stel/Consultas/STFC/PrestadorasCSP/tela.asp?nav=3&c=1&pref=
    • prepare for 9th digit in cellphones from south region http://www.anatel.gov.br/institucional/component/content/article?id=1385

    This change is Reviewable

  • 'animal-sniffer-maven-plugin' changes: version is upgraded and extracted into root pom.xml

    'animal-sniffer-maven-plugin' changes: version is upgraded and extracted into root pom.xml

    Note: this is a maven build improvement.

    Details:

    • plugin version is upgraded: 1.15 -->> 1.17
    • plugin version is removed out of submodules into root pom.xml (i.e. plugin version can be changed easily)
  • Change build rules to stop mobile and fixed-line descs inheriting from the generalDesc element

    Change build rules to stop mobile and fixed-line descs inheriting from the generalDesc element

    Metadata changes: -- Includes the fixed-line IR change that was submitted on open-source but that we hadn't updated the files for until this point of time. -- Drops the "-1" that was erroneously included in possible lengths before (didn't break anything, but was wrong) - it was a possibleLength of a sub-component so got added to the generalDesc possibleLengths -- possibleNumberPattern no longer inherited: we don't use this anyway, we will do another CL soon to stop including it at all in the generated metadata -- exampleNumber is no longer set on fixed-line and mobile elements from the generalDesc

    XML file changes: -- Stopped specifying "NA" and "-1" specifically for fixed-line and mobile blocks; now they are treated as every other type of phone number: if missing, don't fill them in from generalDesc, but leave them missing.

    Code changes: -- Stop using the exampleNumber on generalDesc for non-geo entities, but look at their phonenumber descs - the exampleNumber won't be stored on the generalDesc anymore. This affects porters if they either copied our build logic or used our built metadata in some way; they should update this method in their port too.


    This change is Reviewable

  • Use a system-installed abseil when available

    Use a system-installed abseil when available

    Currently, CMake is configured to download and build abseil from source whenever BUILD_GEOCODER is set to ON. Let's allow users to use a pre-existing installation of abseil by checking for one first before attempting to download and build another one.

    If CMake finds a pre-existing installation of abseil, it will use that instead.

    We need to allow the user to override CMAKE_CXX_STANDARD because they may have built abseil with a newer standard than C++11. Attempting to build libphonenumber with C++11 will fail if abseil was built with a newer C++ standard.

    Closes #2772.

  • Some performance improvements to CPP lib based on absl packages

    Some performance improvements to CPP lib based on absl packages

    @API updates:

    • Migrating from associative containers to more performant types. Eg: map to absl::btree_map.
    • Synchronise the write access to map "AreaCodeMaps" using absl::Mutex locking api.
    • Use more of absl:strings packages like absl::StrReplaceAll

    @Build updates:

    • To build (CMake) against absl packages, the minimum version of compiler is CPP11+, whereas earlier we are not mandating this.
    • We are upgrading CMAKE version also to automate building the external absl packages.

    The change is announced. Please report issues in case of any breakages. https://issuetracker.google.com/issues?q=componentid:192347%20555

  • Update the Netherlands (NL) section

    Update the Netherlands (NL) section

    • Country: Netherlands (NL)
    • Example number(s) and/or range(s): +3197012345678
    • Number type ("fixed-line", "mobile", "short code", etc.): mobile
    • Where or whom did you get the number(s) from: government, https://wetten.overheid.nl/BWBR0010198/2020-04-04
    • Authoritative evidence (e.g. national numbering plan, operator announcement): https://wetten.overheid.nl/BWBR0010198/2020-04-04 (see Appendix 1, in Dutch "Bijlage 1")
    • Link from demo (http://libphonenumber.appspot.com) showing error: https://libphonenumber.appspot.com/phonenumberparser?number=%2B3197012341234&country=NL (it shows isPossibleNumber()==false and TOO_LONG which is invalid. These number are also used for H2H communication (data, sms and/or voice).

    Changes in this PR:

    • update links to more recent and secure versions of wiki / government information
    • update comments for 06[1-58], 067[0-5], 0970
    • add 0970 numbers (12 digits) since they are also available for Human to Human (H2H) communication

    This is an attempt to fix the following (Signal) issues:

    • https://github.com/signalapp/Signal-iOS/issues/4442
    • https://github.com/signalapp/Signal-Android/issues/9005
    • https://issuetracker.google.com/issues/140508060

    Note 0970 are used for data, voice (H2H, M2H), and sms communication. Their usage depends on the telecom operator.

    Please be gentle with me, since this is my first PR for this project.

  • Add new build options

    Add new build options

    This pull request adds two new build options:

    • USE_PROTOBUF_LITE - When this is set to ON then it links against protobuf-lite instead of the full version of protobuf. As far as I could see the metadata has option optimize_for = LITE_RUNTIME; so it should be safe to use the lite version. This is useful when you want to save some disk space. The default is OFF.
    • REGENERATE_METADATA - When this is set to OFF it will skip regenerating the metadata with BuildMetadataCppFromXml. Since the metadata is included in the source tree anyway, it is beneficial for packagers to turn this OFF: it saves some time, and it also makes it unnecessary to have java in the build environment. The default is ON.

    Please let me know what you guys think.

  • Update for Portuguese providers

    Update for Portuguese providers

    Updates from: https://www.anacom.pt/pnn/pesquisa.do. TMN is now MEO and Optimus is now NOS (https://en.wikipedia.org/wiki/List_of_mobile_network_operators_of_Europe#Portugal) 351 92 are distributed according the needs of each provider.

  • Add M2M SIM number falsehood

    Add M2M SIM number falsehood

    Many telephony API providers use libphonenumber to validate phone numbers for voice calls. As libphonenumber does not support M2M sim number validation this prevents M2M sims from receiving phone calls from such telephony providers.

  • Add namespace around utf and rune

    Add namespace around utf and rune

    This is a partial slice of the utf library (see third_party/utf) and the C API does not permit for the full API to be added to Chromium (duplicate symbols).

    Since this should be for libphonenumber usages only, refactoring this to a c++ library with a namespace.

    Ideally, libphonenumber could just depend on the full utf library in third_party (open source) rather than have a custom subset/slice of it.

  • Make abseil-cpp a git submodule

    Make abseil-cpp a git submodule

    Building in environments without network access (e.g. Flatpak, reproducible builds, ...) it is problematic to download sources from CMake. Following recommendations from the abseil documentation of using a git submodule.

    Related issue: https://issuetracker.google.com/issues/230166349

  • isRegionUsingNationalPrefix

    isRegionUsingNationalPrefix

    Reducing the publication of metadata for a region code of https://github.com/google/libphonenumber/pull/2583 by just gaining access to its method hasNationalPrefix as an own method for a given RegionCode.

    This method is directly used in the existing method getLengthOfGeographicalAreaCode where the beginning code is exactly the code needed for this functionality and thus can be replaced by it.

Related tags
A single header C++ library for parsing command line arguments and options with minimal amount of code

Quick Arg Parser Tired of unwieldy tools like getopt or argp? Quick Arg Parser is a single header C++ library for parsing command line arguments

Dec 21, 2022
Dec 27, 2022
A command parsing library

LampOpt操作文档 概述 LampOpt是一个基于C++的控制台命令解析库,优点是体型小、适应全平台、方便易用。 引用 可选择在IDE中直接在引用目录中添加odt.h,或直接与需编译文件放在同一目录下,并引用: #include "odt.h" 使用 odt.h头文件内定义了一个名为LampOp

Aug 21, 2022
Command-line flag parsing in C

flag.h Inspired by Go's flag module: https://pkg.go.dev/flag WARNING! The design of the library is not finished and may be a subject to change. Quick

Nov 10, 2022
easy to use, powerful & expressive command line argument parsing for modern C++ / single header / usage & doc generation

clipp - command line interfaces for modern C++ Easy to use, powerful and expressive command line argument handling for C++11/14/17 contained in a sing

Dec 29, 2022
A lightweight utility for parsing PE file formats (EXE, DLL, SYS) written in C/C++

peParser A lightweight utility for parsing PE file formats (EXE, DLL, SYS). Windows Portable Executable (PE) files includes a variety of parsable data

Dec 10, 2022
A simple header-only C++ argument parser library. Supposed to be flexible and powerful, and attempts to be compatible with the functionality of the Python standard argparse library (though not necessarily the API).

args Note that this library is essentially in maintenance mode. I haven't had the time to work on it or give it the love that it deserves. I'm not add

Jan 4, 2023
A simple header-only C++ argument parser library. Supposed to be flexible and powerful, and attempts to be compatible with the functionality of the Python standard argparse library (though not necessarily the API).

args Note that this library is essentially in maintenance mode. I haven't had the time to work on it or give it the love that it deserves. I'm not add

Aug 31, 2021
A (relatively) small node library to clone and pull git repositories in a standalone manner thanks to libgit2, powered by WebAssembly and Emscripten

simple-git-wasm A (relatively) small node library to clone and pull git repositories in a standalone manner thanks to libgit2, powered by WebAssembly

Oct 16, 2022
A C, C++ and Rust library to draw graphics with pixels in the terminal
A C, C++ and Rust library to draw graphics with pixels in the terminal

A library to draw graphics with pixels in the terminal Who needs a GUI when you have a terminal ? Building To generate libpluto.a, run: $ make To ins

Nov 7, 2022
C++ Library for pulling system and hardware information, without hitting the command line.

infoware C++ Library for pulling system and hardware information, without hitting the command line. Requirements No non-built-in ones by default. Some

Dec 23, 2022
A library for interactive command line interfaces in modern C++
A library for interactive command line interfaces in modern C++

cli A cross-platform header only C++14 library for interactive command line interfaces (Cisco style) Features Header only Cross-platform (linux and wi

Dec 31, 2022
PDCurses - a curses library for environments that don't fit the termcap/terminfo model.

Welcome to PDCurses! PDCurses is an implementation of X/Open curses for multiple platforms. The latest version can be found at: https://pdcurses.org/

Jan 4, 2023
Library for writing text-based user interfaces

IMPORTANT This library is no longer maintained. It's pretty small if you have a big project that relies on it, just maintain it yourself. Or look for

Dec 22, 2022
Small header only C++ library for writing multiplatform terminal applications

Terminal Terminal is small header only library for writing terminal applications. It works on Linux, macOS and Windows (in the native cmd.exe console)

Jan 2, 2023
A single-class C++ library for reading animated GIF files

EasyGifReader EasyGifReader is a single-class C++ library that aims to simplify reading an animated GIF file. It is built on top of and depends on gif

Nov 17, 2022
Library for creating terminal applications with text-based widgets
Library for creating terminal applications with text-based widgets

Library for creating terminal applications with text-based widgets FINAL CUT is a C++ class library and widget toolkit with full mouse support for cre

Dec 30, 2022
The gflags package contains a C++ library that implements commandline flags processing.

The gflags package contains a C++ library that implements commandline flags processing. It includes built-in support for standard types such as string and the ability to define flags in the source file in which they are used. Online documentation available at:

Jan 4, 2023
This is a simple CLI interface helper library for C.

LIBCCLI This is a very simple shell like interface for CLI activities. More will be added to this, but for now, this is the basic idea:

Sep 24, 2022