Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readJava
#Java#String#Regex#Pattern
Illustration of a Java string being validated against a regex pattern with a checkmark, representing the matches method.

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.

java
String input = "abc123"; boolean isAlphanumeric = input.matches("[a-zA-Z0-9]+"); System.out.println(isAlphanumeric); // true

matches() 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:

java
String text = "hello"; System.out.println(text.matches("ell")); // false System.out.println(text.matches("hello")); // true

This 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:

java
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:

java
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:

java
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.

java
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.

java
System.out.println("HELLO".matches("(?i)hello")); // true

When 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.

MethodBehaviorExample use case
matchesFull string matches regexValidate a string format
containsLiteral substring existsCheck if string contains "abc"
startsWithString begins with a prefixCheck a filename prefix
endsWithString ends with a suffixCheck a file extension
regionMatchesCompare a region of the stringCase-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 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.