Java String.matches: How to Use It Effectively
Understand how Java's String.matches method compiles a regex, why it anchors to the whole string, the cost of repeated calls, and when to use Pattern and Matcher instead.

Java's String.matches method is a convenient way to check whether an entire string matches a regular expression. This article explains how the method compiles regexes, why it anchors to the full input, what repeated calls cost, and when to use Pattern and Matcher instead.
How String.matches Works
The String.matches method is a convenience method that tells you whether the entire string matches a given regular expression. Its signature is public boolean matches(String regex). Internally, it calls Pattern.matches(regex, this), which compiles the regex and applies it to the whole string.
String input = "abc123";
boolean isAlphanumeric = input.matches("[a-zA-Z0-9]+");
System.out.println(isAlphanumeric); // truematches() returns true only when the regex matches the whole string. This differs from substring-style regex search, such as Matcher.find(). The full-match behavior is often unexpected if you have used regex in languages where a match can be found anywhere in the input.
The Regex Is Anchored by Default
Because the entire string must match, matches behaves as if the pattern were wrapped in \A and \z. For example:
String text = "hello";
System.out.println(text.matches("ell")); // false
System.out.println(text.matches("hello")); // trueThis anchoring is useful for validation but can surprise you if you expect substring behavior. If you need to check whether a substring matches a pattern, use Pattern.compile(regex).matcher(input).find() instead.
Using String.matches for Input Validation
A typical use case is validating user input. For instance, checking that a string is a positive integer:
public boolean isPositiveInteger(String value) {
return value.matches("\\d+");
}Note the double backslash in the Java string to represent a single backslash in the regex. The pattern \d+ matches one or more digits. Because matches anchors the pattern, this method returns true only when the entire string consists of digits.
Another example is checking a date-like string such as 2025-03-14:
String date = "2025-03-14";
boolean validFormat = date.matches("\\d{4}-\\d{2}-\\d{2}");This validates the format, not the calendar date. For real date validation, use a parsing library or a more elaborate regex.
Performance: Why Repeated Calls Are Costly
Every call to String.matches compiles the regular expression from scratch. Compilation involves parsing the pattern and building an internal state machine, which is relatively expensive compared with the actual matching operation. If you call matches in a loop or on a hot path, this overhead can become significant.
Consider this code that validates a list of strings:
List<String> inputs = List.of("123", "456", "789");
for (String s : inputs) {
if (s.matches("\\d+")) {
// process
}
}Each iteration recompiles the same pattern \d+. For a few elements this is fine, but for thousands or millions of calls, the repeated compilation adds up. The underlying mechanism is that Pattern.matches calls Pattern.compile(regex) and then creates a matcher on each invocation.
Reusing Patterns with Pattern and Matcher
To avoid repeated compilation, compile the pattern once and reuse it. The Pattern class provides a matcher method that returns a Matcher instance, which you can call matches() on.
Pattern digitPattern = Pattern.compile("\\d+");
for (String s : inputs) {
if (digitPattern.matcher(s).matches()) {
// process
}
}This compiles the regex only once. Matcher objects are inexpensive to create. If you reuse a single matcher for multiple inputs, call reset(newInput) before calling matches() again. In practice, creating a new matcher per input is acceptable because compilation is the expensive part.
If you only need to check a single string, String.matches is perfectly fine. The performance concern only becomes relevant when the same pattern is used repeatedly.
Common Pitfalls and Edge Cases
Several edge cases can trip up developers when using String.matches.
Escaping backslashes: In Java string literals, a backslash is an escape character. To write a single backslash in a regex, you need two backslashes in the source code. For example, \d in regex becomes "\\d" in Java.
Null input: If the string on which you call matches is null, the method throws a NullPointerException. There is no overload that accepts a null string.
Invalid regex: If the regex itself is malformed, PatternSyntaxException is thrown. This is a runtime exception, so you should ensure your pattern is correct, especially if it comes from user input.
Empty string: An empty string matches patterns that allow zero characters, such as .* or [a-z]*. It will not match .+ or \d+.
Case sensitivity: By default, matching is case-sensitive. To make it case-insensitive, you can use the inline flag (?i) at the start of the pattern, or compile a Pattern with Pattern.CASE_INSENSITIVE.
System.out.println("HELLO".matches("(?i)hello")); // trueWhen to Choose String.matches Over Other Methods
String.matches is the right tool when you need to verify that the entire string conforms to a pattern. For substring searches, prefix/suffix checks, or simple character comparisons, other methods are more appropriate and often faster.
| Method | Behavior | Example use case |
|---|---|---|
matches | Full string matches regex | Validate a string format |
contains | Literal substring exists | Check if string contains "abc" |
startsWith | String begins with a prefix | Check a filename prefix |
endsWith | String ends with a suffix | Check a file extension |
regionMatches | Compare a region of the string | Case-insensitive substring comparison |
Use matches when you need full-match semantics and the power of regular expressions. If you only need a literal substring, contains is simpler and does not involve regex compilation. For prefix/suffix checks, startsWith and endsWith are direct and efficient.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.