In Java, matches(regex) returns true only when the entire string matches the regular expression, from the first character to the last. A pattern that fits just part of the text is not enough: "abc123".matches("\\d+") is false.
It is the quick way to validate input such as digits only, postal codes, or user names. Behind the scenes it calls Pattern.matches(regex, this), which compiles the pattern on every call.
matches() is an instance method of java.lang.String, added in Java 1.4. Call it on a string, as in text.matches(...); calling it on a null reference throws NullPointerException. It only reads the text; the string itself is never changed.
Syntax
Pass a regex as a Java string. Remember to double every backslash: the regex \d is written "\\d".
java
boolean digits = input.matches("\\d+"); // only digits
boolean zip = code.matches("\\d{5}"); // exactly five digits
boolean yes = answer.matches("(?i)y|yes"); // case-insensitive
Call
What it does
"2026".matches("\\d+")
true: every char is a digit.
"20x6".matches("\\d+")
false: the x breaks the full match.
"abc123".matches(".*\\d.*")
true: "contains a digit" must be written as a full pattern.
"".matches("\\d*")
true: * also allows zero characters.
matches() behaves as if the pattern were wrapped in ^...$. To find a pattern anywhere in the text, use Pattern.compile(regex).matcher(text).find(), or surround it with .* as in the table.
Library declarations
java
public boolean matches(String regex);
Parameters
Parameter
Description
regex
The regular expression the whole string must match. Must not be null.
Return Value
Return Value
Description
true
The complete string matches the pattern.
false
Any character is left unmatched.
Java Examples
Example 1 — The Whole String Must Match
The same digit pattern gives different answers depending on what else is in the string.
java
public class MatchesWholeString {
public static void main(String[] args) {
System.out.println("12345".matches("\\d+"));
System.out.println("123a".matches("\\d+"));
System.out.println("abc123".matches("\\d+"));
System.out.println("abc123".matches(".*\\d+.*"));
}
}
Output
true
false
false
true
How It Works
All digits pass.\d+ means "one or more digits", and "12345" is nothing but digits.
Partial fits fail."123a" and "abc123" contain digits, but the letters are not covered by the pattern, so matches says false.
Allow anything around it..*\d+.* lets any text appear before and after the digits, turning the check into "contains a number".
Example 2 — Validate User Names with One Pattern
A name must start with a lowercase letter, followed by 2 to 11 lowercase letters, digits, or underscores.
java
public class MatchesUsername {
public static void main(String[] args) {
String rule = "[a-z][a-z0-9_]{2,11}";
String[] names = {"ada_99", "bob", "9lives", "Al"};
for (String name : names) {
System.out.println(name + " -> " + (name.matches(rule) ? "valid" : "invalid"));
}
}
}
Output
ada_99 -> valid
bob -> valid
9lives -> invalid
Al -> invalid
How It Works
Read the rule in two parts.[a-z] is the required first letter; [a-z0-9_]{2,11} is 2 to 11 more allowed characters, so a name is 3 to 12 characters long.
Good names."ada_99" (6 chars) and "bob" (3 chars) start with a lowercase letter and use only allowed characters.
Rejected names."9lives" starts with a digit and "Al" starts with a capital and is too short.
Example 3 — Ignore Case with (?i) and Catch a Bad Pattern
An inline flag makes the match case-insensitive; a broken pattern throws at run time.
java
import java.util.regex.PatternSyntaxException;
public class MatchesFlags {
public static void main(String[] args) {
String[] answers = {"YES", "y", "yep"};
for (String a : answers) {
System.out.println(a + " -> " + a.matches("(?i)yes|y"));
}
try {
"abc".matches("[abc");
} catch (PatternSyntaxException e) {
System.out.println("Bad regex: " + e.getClass().getSimpleName());
}
}
}
Output
YES -> true
y -> true
yep -> false
Bad regex: PatternSyntaxException
How It Works
Inline flag.(?i) at the start switches on case-insensitive matching, so "YES" matches the alternative yes.
Alternatives still need a full match."yep" is neither yes nor y in full, so it is rejected.
Syntax errors surface late."[abc" never closes its bracket; the compiler accepts the string, and matches throws PatternSyntaxException when it runs.
Frequently Asked Questions
No. It must match the entire string. "abc123".matches("\d+") is false. Use Matcher.find() or wrap the pattern in .* to search inside the text.
In a Java string literal a single backslash starts an escape sequence, so the regex \d (a digit) must be written as "\\d" inside the quotes.
Add the inline flag (?i) at the start of the pattern, for example answer.matches("(?i)yes").
PatternSyntaxException, an unchecked exception from java.util.regex. A null regex throws NullPointerException.
It compiles the regex on every call. That is fine for a few checks, but in a loop compile a Pattern once with Pattern.compile and reuse it.