How to Match Phone Numbers in a List to a Regex Pattern in Java ?
Last Updated :
24 Apr, 2025
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);
}
}
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
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.
Similar Reads
Java program to read all mobile numbers present in given file
In this article, we are going to discuss a Java program that reads all mobile numbers from a given text file and writes the correct mobile number to another output file. For this, we are going to use regular expression to identify the correct mobile number. Note: The number should meet the correct c
3 min read
How to Convert a Java String Against a Pattern Regex?
Regular expressions, or "regex," are an effective tool in Java programming for checking texts against a given pattern. This post will walk you through the process of utilizing regular expressions to validate a Java text against a pattern. Prerequisites:String in JavaRegular Expressions in JavaConver
2 min read
How to Validate if a String Starts with a Vowel Using Regex in Java?
Regular Expressions in Java allow developers to create patterns for matching strings. In this article, we will learn How to Check whether the Given Character String Starts with a Vowel. Example to Check String is Starting with a VowelInput: "Apple"Output: Is a VowelInput: "Cart"Output: Is not a Vowe
2 min read
How to Remove All Punctuation from a String using Regex in Java?
In this article, we will explain how to remove all punctuation from a given String by using Java with the help of Regex. Here regex means regular expression. The regex is a powerful way to explain the search pattern. One more thing is that regular expressions are mostly used for Searching a required
4 min read
Count Occurrences of a Given Character using Regex in Java
Given a string and a character, the task is to make a function that counts the occurrence of the given character in the string using Regex. Examples: Input: str = "geeksforgeeks", c = 'e' Output: 4 'e' appears four times in str. Input: str = "abccdefgaa", c = 'a' Output: 3 'a' appears three times in
2 min read
How to Replace All Occurings of String Using Regex in Java?
Regex in Java is an interesting way to search for patterns in a string that the user provides. Expanded as Regular Expressions, It consists of some patterns that can be planned and modified according to the usage in the program. Example of Replace All Occurings of a StringInput: str="This is a sampl
2 min read
How to Replace the First Occurrence of a String Using Regex in Java?
Regex is a very interesting way to search for patterns in a String that the user provides. Regex stands for Regular Expressions. It consists of some patterns that can be planned and modified according to the usage of the program. In this article, we will discuss how to replace the first occurrence o
2 min read
Java Program to Search a Particular Word in a String Using Regex
In Java string manipulation, searching for specific words is a fundamental task. Regular expressions (regex) offer a powerful and flexible approach to achieve this search. It matches the patterns simply by comparing substrings. In this article, we will learn how to search for a particular word in a
3 min read
Java Program to Find Occurrence of a Word Using Regex
Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using Re
2 min read
How to Convert a String to ArrayList in Java?
Converting String to ArrayList means each character of the string is added as a separator character element in the ArrayList. Example: Input: 0001 Output: 0 0 0 1 Input: Geeks Output: G e e k s We can easily convert String to ArrayList in Java using the split() method and regular expression. Paramet
1 min read