Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Matcher matches() Method Explained

Learn how Java's Matcher.matches() checks an entire string against a regex pattern, compare it with find() and lookingAt(), see validation examples, and avoid common mistakes.

~5 min readJava
#Java regex#Matcher#Pattern#String validation
Java Matcher matches() method comparing a regex pattern to a full string, with a checkmark indicating a successful full match.

When you need to verify that an entire string conforms to a specific format, Java's Matcher.matches() is the method to use. Unlike find(), which searches for a pattern anywhere in the input, matches() requires the whole input sequence to match the pattern. This distinction is critical for tasks like validating email addresses, phone numbers, or user identifiers where partial matches are not acceptable.

matches() is part of the java.util.regex.Matcher class, which you obtain from a compiled Pattern object. The typical usage is:

java
Pattern pattern = Pattern.compile("\\d{3}-\\d{2}-\\d{4}"); Matcher matcher = pattern.matcher("123-45-6789"); boolean isMatch = matcher.matches();

Here, isMatch is true because the entire string 123-45-6789 matches the pattern for a Social Security number format. If the input had any extra characters, such as a trailing space or a leading letter, matches() would return false.

What Does matches() Actually Check?

matches() attempts to match the entire input sequence against the pattern. In effect, the match must start at the beginning of the input and end at the end of the input. This is different from lookingAt(), which anchors only the start, and find(), which has no anchors at all.

Consider the pattern cat. With matches(), the input cat returns true, but category returns false because the pattern does not cover the entire string. With find(), both cat and category return true because the pattern appears as a substring.

How matches() Differs from find()

The most common source of confusion is the difference between matches() and find(). While matches() demands a full match, find() scans the input for the next subsequence that matches the pattern. This distinction affects both the result and the matcher's internal state.

Here is a side-by-side example:

java
Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher("Order 123 shipped"); boolean found = matcher.find(); // true, finds "123" boolean matched = matcher.matches(); // false, entire string is not digits

After a successful find(), the matcher's position is set to the end of the matched subsequence, so subsequent find() calls continue from there. matches() is not designed for repeated scanning; it either matches the entire input or fails.

Using matches() for Input Validation

A practical use case for matches() is validating user input before processing. For example, checking that a string contains only alphanumeric characters and is exactly 8 characters long:

java
public boolean isValidUsername(String username) { Pattern pattern = Pattern.compile("[a-zA-Z0-9]{8}"); return pattern.matcher(username).matches(); }

The pattern [a-zA-Z0-9]{8} requires exactly 8 characters, and because matches() enforces the full string, any shorter or longer input is rejected. This is a concise way to enforce format constraints without manually checking length and character classes separately.

For more complex validation, such as an email address, you can use a pattern like [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} and call matches(). Keep in mind that regex-based email validation has limitations; it does not fully implement RFC 5322, and a more robust parser may be needed for production systems.

Common Mistakes with matches()

One frequent mistake is forgetting that matches() requires the entire string to match. Developers who are used to find() may expect matches() to return true when the pattern appears anywhere. For example:

java
Pattern pattern = Pattern.compile("\\d+"); System.out.println(pattern.matcher("abc123").matches()); // false

This returns false because the string contains non-digit characters. To find a pattern that can appear anywhere, use find().

Another common mistake is using matches() on a string with leading or trailing whitespace. The regex \d+ fails on input such as ' 123 ' because the spaces are part of the input. In such cases, trim the input or include \s* in the pattern.

Because matches() already anchors the match to the full input, explicit ^ and $ anchors are redundant in the default mode. With Pattern.MULTILINE, however, they can also match at line boundaries. Since matches() must consume the entire input, an expression that stops at an internal line break can fail even if the prefix would match. Test with representative line breaks.

Performance Considerations

Compiling a Pattern is relatively expensive. Each call to Pattern.compile() creates a new pattern object and compiles the regex into an internal representation. When you validate many strings with the same pattern, reuse the Pattern instance:

java
private static final Pattern USERNAME_PATTERN = Pattern.compile("[a-zA-Z0-9]{8}"); public boolean isValidUsername(String username) { return USERNAME_PATTERN.matcher(username).matches(); }

This avoids repeated compilation overhead. The Matcher object is lightweight and can be created per call, but if you want to reuse one matcher for multiple inputs, call matcher.reset(newInput) instead of creating a new instance.

The complexity of the regex itself also matters. Patterns with catastrophic backtracking can cause severe performance degradation, especially when used with matches() on long strings. If you validate untrusted user input, prefer simpler patterns and avoid nested quantifiers. Java's standard regex engine does not provide a built-in timeout, so design patterns carefully for high-throughput paths.

When to Use matches() vs lookingAt() vs find()

MethodAnchoringUse Case
matches()Full stringValidating the entire input format
lookingAt()Start onlyChecking whether a string starts with a pattern
find()AnywhereSearching for substrings

Use matches() when the entire input must conform to the pattern, such as validating form fields or parsing fixed-format data. Use lookingAt() when you need to check that a string starts with a pattern, with or without additional content after the match. Use find() when you need to locate one or more occurrences of a pattern within a larger text.

A common pattern in parsers is to use find() to extract tokens and then use matches() on each token to validate its format. This combination leverages the strengths of both methods.

Handling Edge Cases with matches()

One edge case is an empty input string. For a pattern like .*, matches() returns true for an empty string because .* matches zero characters. For a pattern like \d+, it returns false because at least one digit is required. This behavior is consistent with regex semantics, but it can surprise developers who expect an empty string to fail validation. If you want to reject empty strings, include a quantifier such as + or {n,m} that requires at least one character.

Another edge case is line terminators and the Pattern.UNIX_LINES flag. Flags can change the definition of a line terminator and the behavior of ^ and $. Even though matches() requires the entire input, a pattern using line-break anchors may behave differently on input containing newline characters. Test your regexes with representative inputs, including empty strings, strings with whitespace, and strings with newline characters.

A Complete Validation Example

Here is a complete example that validates a date in the YYYY-MM-DD format using matches():

java
import java.util.regex.Pattern; public class DateValidator { private static final Pattern DATE_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}"); public static boolean isValidDate(String date) { return DATE_PATTERN.matcher(date).matches(); } public static void main(String[] args) { System.out.println(isValidDate("2023-12-31")); // true System.out.println(isValidDate("2023-12-31T10:00")); // false System.out.println(isValidDate("2023-13-01")); // true (format only, not calendar validity) } }

This regex checks only the format, not whether the month or day values are valid. For calendar validation, you would need additional logic. The key point is that matches() ensures the entire string has the expected format, which is often the first step in input validation.

In production, you might combine matches() with additional checks for semantic validity. For instance, after confirming the format, parse the date and verify that the month is between 1 and 12 and that the day is appropriate for the month. This separation of concerns keeps validation logic clear and maintainable.

matches() is a boolean operation; it does not report why a match failed. If you need to tell users which part of the input is invalid, use find() with a more granular pattern or inspect the input manually. For many validation scenarios, a simple true/false result is sufficient, and matches() provides a clean and efficient way to get it.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.