Open In App

How to Match Phone Numbers in a List to a Regex Pattern in Java ?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Regular Expressions are also known as regex or regexp. It is one of the powerful features of Java that helps in sequences of characters that define a search pattern. Nowadays it is widely used in computer science, programming, and text processing for tasks such as string matching, data extraction, and validation. In Java, the “java.util.regex” package set of tools for pattern matching.

In this article, we will learn how to match phone numbers in a list to a certain pattern using regex.

Java Program to Match Phone Numbers in the List to Regex Pattern

Step 1: Import All the Necessary Packages

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java. util.List;

Step 2: Define the Regex Pattern using Tokens in Java

Phone number contains only numeric value and some special characters according to countries. For example, Let’s take a U.S. phone number.

Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java. util.List;

class GFG {
    public static void main (String[] args) {
      
      String phoneNumberPattern = "\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b";
        
    }
}


Step 3: Create a method Match Phone Numbers

 public static void matcher(List<String> phoneNumbers)

Program to Match Phone Numbers in a List

Approach 1: Using Regex

Now create a separate method in class to Match Phone Numbers which are store in List.

Java
// Java Program to Match Phone 
// Numbers in a List Using Regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;

public class PhoneNumberMatcher {

    // Created Macher function
    public static void matcher(List<String> phoneNumbers)
    {

        // created phone number pattern using tokens
        String phoneNumberPattern
            = "\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b";

        // Compile the custom pattern using Pattern class
        Pattern pattern
            = Pattern.compile(phoneNumberPattern);

        // Using for each loop check each element in list
        for (String phoneNumber : phoneNumbers) {
          
          //Using Matcher class matching phone number
          Matcher matcher = pattern.matcher(phoneNumber);
          if (matcher.matches()) {
            System.out.println("Match: " + phoneNumber);
            }
            else {
                System.out.println("Not a Match: "
                                   + phoneNumber);
            }
        }
    }
    public static void main(String[] args)
    {
        //List of U.S phone numbers
        List<String> phoneNumbers
            = List.of("123-456-7890", "987.654.3210",
                      "555-1234", "1234567890");
      
      // Calling each method against the pattern
      matcher(phoneNumbers);
    }
}

Output
Match: 123-456-7890
Match: 987.654.3210
Not a Match: 555-1234
Match: 1234567890


Approach 2: Using Matches

The matches() method is a convenient method provided by the String class in Java for checking if a string matches a given regular expression. When we use this method, we don’t need to explicitly create a Matcher object from the Pattern class; the method internally takes care of that.

Old Approach (Using Matcher):

Pattern pattern = Pattern.compile(phoneNumberPattern);
Matcher matcher = pattern.matcher(phoneNumber);
if (matcher.matches()) {
    // Do something when the string matches the pattern
} else {
    // Do something else when the string does not match the pattern
}

Using matches() directly on the string:

if (phoneNumber.matches(phoneNumberPattern)) {
    // Do something when the string matches the pattern
} else {
    // Do something else when the string does not match the pattern
}

In the second approach, the matches() method is called directly on the string (phoneNumber), and it internally creates a Matcher object, applies the pattern, and checks if the entire string matches the pattern. It simplifies the code and is often more concise.

Java
// Java Program to Match Phone 
// Numbers in a List Using matches() method
import java.util.List;

public class PhoneNumberMatcher {

    // Created Macher function
    public static void matcher(List<String> phoneNumbers) {

        // created phone number pattern using tokens
        String phoneNumberPattern = "\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b";

        // Using for each loop check each element in list
        for (String phoneNumber : phoneNumbers) {
            // Using matches() directly on the string
            if (phoneNumber.matches(phoneNumberPattern)) {
                System.out.println("Match: " + phoneNumber);
            } else {
                System.out.println("Not a valid U.S. phone number: " + phoneNumber);
            }
        }
    }

    public static void main(String[] args) {
        // List of U.S phone numbers
        List<String> phoneNumbers = List.of("123-456-7890", "987.654.3210", "555-1234", "1234567890");

        // Calling each method against the pattern
        matcher(phoneNumbers);
    }
}
//This Code is Contributed by Ayan Ahmad

Output
Match: 123-456-7890
Match: 987.654.3210
Not a valid U.S. phone number: 555-1234
Match: 1234567890

Explanation of the Program:

  • Checking stored Phone Numbers in a list to a specific pattern using Regular Expression help in flexible and scalable for validating or extracting specific formats of data we use regular expression pattern.
  • Customize the regex pattern helps to match critical as per your requirement.
  • This approach is used in every kind of form validation before store data into database.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads