Java Regex Phone Number validation Example

This Java regex example demonstrates how to use regular expressions to validate phone numbers in Java with an example.

Regular Expression Phone Number validation

Validating a phone number using regular expression is tricky because the phone number can be written in many formats and can have extensions also.
For example, here are some of the common way of writing phone numbers:
1234567890 
123-456-7890 
123-456-7890 x1234 
123-456-7890 ext1234 
(123)-456-7890 
123.456.7890 
123 456 7890
Here is the Java program to demonstrates how to use a regular expression to validate phone numbers:
package net.javaguides.corejava.regex;

public class CheckPhoneExample {

    public static void main(String[] args) {
        System.out.println("Phone number 1234567890 validation result: " + validatePhoneNumber("1234567890"));
        System.out.println("Phone number 123-456-7890 validation result: " + validatePhoneNumber("123-456-7890"));
        System.out.println(
            "Phone number 123-456-7890 x1234 validation result: " + validatePhoneNumber("123-456-7890 x1234"));
        System.out.println(
            "Phone number 123-456-7890 ext1234 validation result: " + validatePhoneNumber("123-456-7890 ext1234"));
        System.out.println("Phone number (123)-456-7890 validation result: " + validatePhoneNumber("(123)-456-7890"));
        System.out.println("Phone number 123.456.7890 validation result: " + validatePhoneNumber("123.456.7890"));
        System.out.println("Phone number 123 456 7890 validation result: " + validatePhoneNumber("123 456 7890"));
    }

    private static boolean validatePhoneNumber(String phoneNo) {
        // validate phone numbers of format "1234567890"
        if (phoneNo.matches("\\d{10}"))
            return true;
        // validating phone number with -, . or spaces
        else if (phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}"))
            return true;
        // validating phone number with extension length from 3 to 5
        else if (phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}"))
            return true;
        // validating phone number where area code is in braces ()
        else if (phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}"))
            return true;
        // return false if nothing matches the input
        else
            return false;

    }
}
Output:
Phone number 1234567890 validation result: true
Phone number 123-456-7890 validation result: true
Phone number 123-456-7890 x1234 validation result: true
Phone number 123-456-7890 ext1234 validation result: true
Phone number (123)-456-7890 validation result: true
Phone number 123.456.7890 validation result: true
Phone number 123 456 7890 validation result: true

References

Comments