![]() |
VOOZH | about |
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.
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.
Step 3: Create a method Match Phone Numbers
public static void matcher(List<String> phoneNumbers)Now create a separate method in class to Match Phone Numbers which are store in List.
Match: 123-456-7890 Match: 987.654.3210 Not a Match: 555-1234 Match: 1234567890
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.
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
}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.
Match: 123-456-7890 Match: 987.654.3210 Not a valid U.S. phone number: 555-1234 Match: 1234567890