The String.matches() method evaluates whether an entire string matches a specified regular expression pattern, returning a boolean result.
Full-String Anchoring & Regex Syntax: Crucially, matches() requires the entire string to match the pattern, not just a partial substring. For unanchored literal substring searches, see contains(). For prefix and suffix matching, explore startsWith() and endsWith(). To split strings by regex, see split(), or perform regex replacements with replaceAll().
The matches() method is defined in java.lang.String:
// Formal signature of String.matches() in java.lang.String
public boolean matches(String regex)
| Parameter / Element | Type | Description & Operational Rule |
|---|---|---|
regex |
String |
The regular expression pattern to test against the entire string. |
| Return Value | boolean |
Returns true if the entire string matches the pattern; false otherwise. |
| Exception | Runtime | Throws PatternSyntaxException if the regex pattern is syntactically invalid. |
Validating whether text conforms to strict character sets such as numeric digits:
String input1 = "12345";
String input2 = "123a45";
// Matches if the ENTIRE string consists of one or more digits
System.out.println("input1 is numeric: " + input1.matches("\\d+")); // true
System.out.println("input2 is numeric: " + input2.matches("\\d+")); // falseTerminal Output:
input1 is numeric: true
input2 is numeric: false
In Java, str.matches(regex) evaluates as if the pattern is automatically wrapped with ^...$ anchors. To test for substring presence, use wildcards or contains():
String log = "Error: Database timeout on port 5432";
// 1. Partial pattern FAILS because matches() anchors to start and end
System.out.println("matches('Error'): " + log.matches("Error")); // false
// 2. Unanchored pattern SUCCEEDS by wrapping with .* wildcards
System.out.println("matches('.*Error.*'): " + log.matches(".*Error.*")); // true
// 3. For simple substring checks, contains() is preferred (faster, no regex)
System.out.println("contains('Error'): " + log.contains("Error")); // trueTerminal Output:
matches('Error'): false
matches('.*Error.*'): true
contains('Error'): true
Because str.matches() re-compiles the regex on every execution, high-throughput applications should precompile a static Pattern:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
// 1. String.matches(): re-compiles regex pattern on EVERY single call!
boolean slow = "user_2026".matches("^[a-z]+_\\d+$");
// 2. Precompiled Pattern: compiled ONCE, reused across all threads
Pattern pattern = Pattern.compile("^[a-z]+_\\d+$");
boolean fast = pattern.matcher("user_2026").matches();
System.out.println("matches() result: " + slow);
System.out.println("precompiled result: " + fast);Terminal Output:
matches() result: true
precompiled result: true
Choosing the appropriate inspection method saves CPU cycles and improves clarity:
| Method | Matching Type | Primary Use Case & Efficiency |
|---|---|---|
str.matches(regex) |
Full-string regular expression. | Complex format validation (emails, phone numbers, UUIDs). Slower. |
str.contains(seq) |
Literal substring anywhere. | Fast boolean keyword presence check in O(N) time. |
str.indexOf(seq) |
Literal index position. | Finding cut coordinates for slicing with substring(). |
Calling matches() on a null string throws a NullPointerException. Guard against crashes using null checks:
String input = null;
// RISKY: Calling matches() on null throws NullPointerException
try {
System.out.println(input.matches("\\d+"));
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException on null input!");
}
// SAFE APPROACH: Short-circuit null check
boolean safeCheck = (input != null && input.matches("\\d+"));
System.out.println("Safe check: " + safeCheck);Terminal Output:
Caught NullPointerException on null input!
Safe check: false
Restricting username registrations to alphanumeric characters and underscores between 3 and 16 characters:
public class UsernameValidator {
// Alphanumeric + underscore, length 3 to 16 characters
private static final String USERNAME_REGEX = "^[a-zA-Z0-9_]{3,16}$";
public static boolean isValidUsername(String username) {
if (username == null) return false;
return username.matches(USERNAME_REGEX);
}
public static void main(String[] args) {
System.out.println("user_99: " + isValidUsername("user_99")); // true
System.out.println("ab: " + isValidUsername("ab")); // false (too short)
System.out.println("john doe: " + isValidUsername("john doe")); // false (contains space)
System.out.println("admin@site: " + isValidUsername("admin@site")); // false (invalid char)
}
}Terminal Output:
user_99: true
ab: false
john doe: false
admin@site: false
Validating telephone numbers across common international and formatted conventions:
public class PhoneValidator {
// Standard format: optional +country, 3-3-4 digit blocks
private static final String PHONE_REGEX = "^\\+?[0-9]{1,3}?[-.\\s]?\\(?[0-9]{3}\\)?[-.\\s]?[0-9]{3}[-.\\s]?[0-9]{4}$";
public static boolean isValidPhone(String phone) {
if (phone == null) return false;
return phone.matches(PHONE_REGEX);
}
public static void main(String[] args) {
System.out.println("Phone 1: " + isValidPhone("123-456-7890")); // true
System.out.println("Phone 2: " + isValidPhone("+1 (555) 234-5678")); // true
System.out.println("Phone 3: " + isValidPhone("invalid_phone")); // false
}
}Terminal Output:
Phone 1: true
Phone 2: true
Phone 3: false
Developers coming from other languages often expect "abc".matches("b") to return true. In Java, matches() demands a full-string match. It returns false unless written as ".*b.*".
Using str.matches(...) inside a tight loop repeatedly invokes Pattern.compile(), severely degrading throughput. Use a precompiled static final Pattern.
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringMatchesFullDemo {
public static void main(String[] args) {
String hexColor = "#FFA500";
// 1. Verify hex color format
if (hexColor.matches("^#[0-9a-fA-F]{6}$")) {
System.out.println("Check 1 Passed: Hex color code format valid.");
}
// 2. Full match behavior: partial matching returns false
if (!"Hello World".matches("Hello")) {
System.out.println("Check 2 Passed: Partial pattern correctly returned false.");
}
// 3. Whole match with wildcard
if ("Hello World".matches("Hello.*")) {
System.out.println("Check 3 Passed: Wildcard pattern matched whole string.");
}
System.out.println("All String.matches() verification tests passed successfully!");
}
}Terminal Output:
Check 1 Passed: Hex color code format valid.
Check 2 Passed: Partial pattern correctly returned false.
Check 3 Passed: Wildcard pattern matched whole string.
All String.matches() verification tests passed successfully!
Either wrap the regex with wildcards (".*pattern.*") or use Pattern.compile("pattern").matcher(str).find().
Java throws an unchecked PatternSyntaxException at runtime if the regex string cannot be compiled.
No. matches() strictly requires a String regex pattern.
Yes, regex matching is case-sensitive by default. For case-insensitive validation, prefix your regex with (?i), e.g. "(?i)^[a-z]+$".
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.