How to Check If a String Matches a Phone Number Format in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string matches a phone number format in Java using Regular Expressions (Regex). We will start by creating a Regex pattern specifically designed to match common phone number formats.

Following that, you will validate a given phone number string against the created Regex pattern using Java's Matcher class. Finally, you will explore how to handle and match different variations of phone number formats by adjusting the Regex pattern.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java/StringManipulationGroup -.-> java/regex("RegEx") subgraph Lab Skills java/regex -.-> lab-559991{{"How to Check If a String Matches a Phone Number Format in Java"}} end

Create Phone Number Regex

In this step, we will learn about Regular Expressions (Regex) and how to create one to match phone numbers. Regex is a powerful tool used for pattern matching in strings. It's like a special language for describing text patterns.

Why do we need Regex for phone numbers? Phone numbers can come in many formats (e.g., 123-456-7890, (123) 456-7890, 123.456.7890). Regex allows us to define a pattern that matches all these variations.

Let's create a simple Java program that uses Regex to check if a string looks like a phone number.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class HelloJava {
        public static void main(String[] args) {
            String phoneNumber = "123-456-7890"; // The string to check
            String regex = "\\d{3}-\\d{3}-\\d{4}"; // The regex pattern
    
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(phoneNumber);
    
            boolean isMatch = matcher.matches();
    
            if (isMatch) {
                System.out.println(phoneNumber + " is a valid phone number format.");
            } else {
                System.out.println(phoneNumber + " is not a valid phone number format.");
            }
        }
    }

    Let's look at the new parts of this code:

    • import java.util.regex.Matcher; and import java.util.regex.Pattern;: These lines import the necessary classes for working with Regex in Java.
    • String phoneNumber = "123-456-7890";: This is the string we want to test.
    • String regex = "\\d{3}-\\d{3}-\\d{4}";: This is our first Regex pattern. Let's break it down:
      • \\d: Matches any digit (0-9). We use \\ because \ is a special character in Java strings, so we need to escape it.
      • {3}: Matches the previous element exactly 3 times.
      • -: Matches the hyphen character literally.
      • So, \\d{3}-\\d{3}-\\d{4} matches three digits, followed by a hyphen, followed by three digits, followed by a hyphen, followed by four digits.
    • Pattern pattern = Pattern.compile(regex);: This compiles the Regex string into a Pattern object, which is more efficient for repeated matching.
    • Matcher matcher = pattern.matcher(phoneNumber);: This creates a Matcher object that will perform the matching operation on our phoneNumber string using the compiled pattern.
    • boolean isMatch = matcher.matches();: This attempts to match the entire input string (phoneNumber) against the pattern. It returns true if the entire string matches, and false otherwise.
    • The if and else block simply prints a message based on whether the string matched the pattern.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program in the Terminal:

    javac HelloJava.java

    If there are no errors, a HelloJava.class file will be created.

  5. Run the compiled program:

    java HelloJava

    You should see the output indicating that "123-456-7890" is a valid phone number format according to our simple Regex.

In this step, you've learned the basics of using Regex in Java and created a simple pattern to match a specific phone number format. In the next steps, we'll make our Regex more flexible to handle different formats.

Validate Phone Number with Matcher

In the previous step, we created a simple Regex pattern and used the matches() method of the Matcher class to check if an entire string matched the pattern. In this step, we will explore the Matcher class further and see how it works.

The Matcher class is the engine that performs the matching operations. It's created from a Pattern object and is used to find occurrences of the pattern within an input string.

Let's modify our program to test a different string and see how the matches() method behaves.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Change the phoneNumber string to something that does not exactly match our current pattern \\d{3}-\\d{3}-\\d{4}. For example, change the line:

    String phoneNumber = "123-456-7890"; // The string to check

    to:

    String phoneNumber = "My phone number is 123-456-7890."; // The string to check
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    This time, the output should be:

    My phone number is 123-456-7890. is not a valid phone number format.

    Why did this happen? Because the matches() method attempts to match the entire input string against the pattern. Since our input string contains more than just the phone number pattern, matches() returns false.

    If we wanted to find if the pattern exists anywhere within the string, we would use a different method, like find(), which we will explore later. For now, we are focusing on validating if the entire string conforms to a specific format using matches().

    Understanding the difference between matches() and find() is crucial when working with Regex in Java. matches() is for strict validation of the whole string, while find() is for searching for the pattern within a larger string.

In this step, you've seen how the matches() method of the Matcher class works and why it's important to understand its behavior when validating string formats.

Handle Different Phone Formats

In the real world, phone numbers don't always follow the exact XXX-XXX-XXXX format. They might use dots (.), spaces ( ), or even parentheses (()). In this step, we will modify our Regex pattern to handle some of these variations.

We will introduce a few more Regex concepts to make our pattern more flexible:

  • ?: Makes the preceding element optional (0 or 1 time).
  • *: Matches the preceding element zero or more times.
  • +: Matches the preceding element one or more times.
  • []: Defines a character set. Matches any single character within the brackets.
  • |: Acts as an OR operator. Matches either the pattern before or after the |.

Let's update our HelloJava.java file to use a more flexible Regex pattern.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Change the regex string to the following:

    String regex = "\\(?\\d{3}\\)?[-.\\s]?\\d{3}[-.\\s]?\\d{4}"; // More flexible regex pattern

    Let's break down this new pattern:

    • \\(?: Matches an optional opening parenthesis (. We need \\ to escape the special meaning of ( in Regex, and ? makes it optional.
    • \\d{3}: Matches exactly three digits.
    • \\)?: Matches an optional closing parenthesis ).
    • [-.\\s]?: This is a character set [] that matches either a hyphen (-), a dot (.), or a whitespace character (\\s). The ? makes this separator optional.
    • \\d{3}: Matches exactly three digits.
    • [-.\\s]?: Matches an optional hyphen, dot, or whitespace separator again.
    • \\d{4}: Matches exactly four digits.

    This pattern can now match formats like 123-456-7890, (123) 456-7890, 123.456.7890, 123 456 7890, and even 1234567890 (without any separators).

  3. Now, let's test this new pattern with different phone number formats. Replace the phoneNumber string with a few different examples:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class HelloJava {
        public static void main(String[] args) {
            String[] phoneNumbers = {
                "123-456-7890",
                "(123) 456-7890",
                "123.456.7890",
                "123 456 7890",
                "1234567890",
                "invalid-number", // This should not match
                "123-456-789" // This should not match
            };
    
            String regex = "\\(?\\d{3}\\)?[-.\\s]?\\d{3}[-.\\s]?\\d{4}"; // More flexible regex pattern
    
            Pattern pattern = Pattern.compile(regex);
    
            for (String phoneNumber : phoneNumbers) {
                Matcher matcher = pattern.matcher(phoneNumber);
                boolean isMatch = matcher.matches();
    
                if (isMatch) {
                    System.out.println(phoneNumber + " is a valid phone number format.");
                } else {
                    System.out.println(phoneNumber + " is not a valid phone number format.");
                }
            }
        }
    }

    We've introduced a String array phoneNumbers to easily test multiple inputs and a for loop to iterate through them.

  4. Save the file (Ctrl+S or Cmd+S).

  5. Compile the program in the Terminal:

    javac HelloJava.java
  6. Run the compiled program:

    java HelloJava

    You should see output similar to this, showing which strings match the pattern:

    123-456-7890 is a valid phone number format.
    (123) 456-7890 is a valid phone number format.
    123.456.7890 is a valid phone number format.
    123 456 7890 is a valid phone number format.
    1234567890 is a valid phone number format.
    invalid-number is not a valid phone number format.
    123-456-789 is not a valid phone number format.

You've now created a more robust Regex pattern that can handle several common phone number formats. This demonstrates the power and flexibility of Regex for validating and parsing strings.

Summary

In this lab, we learned how to check if a string matches a phone number format in Java using Regular Expressions (Regex). We started by understanding the concept of Regex and its importance for pattern matching, especially for handling various phone number formats. We then created a simple Java program utilizing the java.util.regex package.

The first step involved creating a basic Regex pattern \\d{3}-\\d{3}-\\d{4} to match the format "XXX-XXX-XXXX". We used Pattern.compile() to compile the regex into a Pattern object and Pattern.matcher() to create a Matcher object for the input string. Finally, we used matcher.matches() to check if the entire string matched the pattern and printed the result. This laid the foundation for validating phone numbers using Regex in Java.