String matches() Method in Java with Examples
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 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);
}
}
Output
true
Table of Content
Syntax of matches() method
boolean matches(String regex)
Parameter:
- regex: The regular expression to match against the string.
Return Type:
- It returns
true
if the string matches the regex, otherwisefalse
.
Other Examples of String matches()
Method
1. Check for Alphabets using matches()
We will use matches() method to check if a string contains only alphabetic characters.
// 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);
}
}
Output
true
2. Validate an Email Address using matches()
To validate an email addresses, regular expressions can be used with matches() method.
// Java program to validate an email address
import java.util.*;
public class StringMatches {
public static void main(String[] args) {
String email = "[email protected]";
// 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);
}
}
Output
true
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 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);
}
}
Output
true
Points to Remember
- The
matches()
method is an efficient way to check if a string is in a specified pattern. - By default, it is case-sensitive.
- Regular expressions are required for defining the patterns.