Phone number regex Java

Phone number

The regular expressions below can be used to validate if a string is a valid phone number format and to extract a phone number from a string. Please note that this validation can not tell if a phone number actually exists.

The basic international phone number validation

A simple regex to validate string against a valid international phone number format without delimiters and with an optional plus sign:

Pattern.compile("^\\+?[1-9][0-9]{7,14}$")

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Example code in Java

import java.util.regex.Pattern;
import java.util.regex.MatchResult;

public class Main {

    public static void main(String []args) {
        // Validate phone number
        boolean isMatch = Pattern.compile("^\\+?[1-9][0-9]{7,14}$")
               .matcher("+12223334444")
               .find(); // returns true
        
        // Extract a phone number from a string
        String[] matches = Pattern.compile("\\+?[1-9][0-9]{7,14}")
                          .matcher("You can reach me out at +12223334444 and +56667778888")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new); // returns ["+12223334444", "+56667778888"]
    }
}

The more complex phone number validation

This regular expression will match phone numbers entered with delimiters (spaces, dots, brackets, etc.)

Pattern.compile("^\\+?\\d{1,4}?[-.\\s]?\\(?\\d{1,3}?\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}$")

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Example code in Java

import java.util.regex.Pattern;
import java.util.regex.MatchResult;

public class Main {

     public static void main(String []args) {
        // Validate phone number
        boolean isMatch = Pattern.compile("^\\+?\\d{1,4}?[-.\\s]?\\(?\\d{1,3}?\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}$")
               .matcher("+1 (615) 243-5172")
               .find(); // returns true
    
     }
}

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Extra information about validating phone number

While validation of phone numbers using regex can give a possibility to check the format of the phone number, it does not guarantee that the number exists.

There might be also an option to leave a phone number field without any validation since some users might have:

  • More complex phone numbers with extensions
  • The different phone numbers for calling them on a different time of day