Last Updated : 20 Nov, 2024
In Java, the matches()
method in the String
class checks if a string matches a specified regular expression. It is useful for validating input patterns and searching within strings.
In this article, we will learn how to use the matches()
method effectively in Java with examples to illustrate its functionality.
Example:
In this example, we will check if a string contains only digits.
Java
// Java program to demonstrate matches() method
import java.util.*;
public class StringMatches {
public static void main(String[] args) {
// Declare and initialize a String
String s = "12345";
// Check if the string matches the regex for digits
boolean r = s.matches("\\d+"); // Matches one or more digits
System.out.println("" + r);
}
}
Syntax of matches() method
boolean matches(String regex)
Parameter:
Return Type:
true
if the string matches the regex, otherwise false
.matches()
Method 1. Check for Alphabets using matches()
We will use matches() method to check if a string contains only alphabetic characters.
Java
// Java program to check if a string contains only alphabets
import java.util.*;
public class StringMatches {
public static void main(String[] args) {
String s = "JavaProgramming";
// Check if the string contains only alphabets
boolean r = s.matches("[a-zA-Z]+"); // Matches only alphabets (case-insensitive)
System.out.println("" + r);
}
}
2. Validate an Email Address using matches()
To validate an email addresses, regular expressions can be used with matches() method.
Java
// Java program to validate an email address
import java.util.*;
public class StringMatches {
public static void main(String[] args) {
String email = "example@domain.com";
// Check if the string is a valid email address
boolean r = email.matches("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
System.out.println("" + r);
}
}
3. Check a String Pattern using matches()
To check whether a string follows a specific pattern like combination of digits or letters, we can use matches() method of String class.
Java
// Java program to check if a string follows a specific pattern
import java.util.*;
public class StringMatches {
public static void main(String[] args) {
String s = "Java123";
// Check if the string contains alphabets followed by digits
boolean r = s.matches("[A-Za-z]+\\d+");
System.out.println("" + r);
}
}
Points to Remember
matches()
method is an efficient way to check if a string is in a specified pattern.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4