Java String matches(): How Regex Matching Works

How-to basics · Updated November 22, 2026

In Java, String.matches(String regex) returns true only when the entire string matches the supplied regular expression. It does not merely check whether the string contains a matching substring; use Matcher.find() for that.

What String.matches() Does

The method is part of Java’s String class and accepts one argument: a regular expression. It returns a boolean, so it is useful in conditions, validation checks, and tests. For example, "cobalt".matches("cobalt") is true, while "cobalt blue".matches("cobalt") is false because the second string has extra characters.

The key detail is that the regular expression must account for the whole input. That behavior is sometimes called a full-string match. The method is effectively based on Pattern.matches(regex, this), which creates a regex pattern and checks whether it matches the complete input.

A simple call might look like this:

String code = "AB123";
boolean valid = code.matches("[A-Z]{2}[0-9]{3}");
System.out.println(valid); // true

The expression permits exactly two uppercase letters followed by exactly three digits. A longer value such as "AB1234" does not match, even though its first five characters fit the pattern.

Why a Match Must Cover the Whole String

Java’s matches() method behaves differently from a search operation. The expression "cat" matches the string "cat", but not "a cat sleeps". To make the latter string match with matches(), the expression would need to allow characters before and after the word, such as ".*cat.*".

That distinction prevents a common validation bug. Suppose an application checks whether a value contains only digits with value.matches("[0-9]+"). Because the expression must match the whole value, "4827" passes and "48x27" fails. If the check were instead a search for one or more digits, the second value could produce a match simply because it contains some digits.

Explicit start and end anchors are usually unnecessary for this method. For example, "[A-Z]+" already has to match the complete string when passed to matches(). Anchors such as ^ and $ are more commonly useful with search operations, where the regex engine otherwise looks for a match somewhere in the input.

How to Write Common Matching Patterns

A regular expression describes a pattern, not a literal string in every case. Characters such as ., *, +, ?, brackets, and parentheses have special meanings in regex syntax. For instance, . normally matches a character, while [.] means a literal period.

Here are practical examples of full-string checks:

  • "[0-9]+" accepts one or more ASCII digits, such as "7" or "2048".
  • "[A-Za-z]+" accepts one or more basic English letters, but not spaces or accented letters.
  • "[A-Z]{2}[0-9]{3}" accepts exactly two uppercase letters followed by three digits.
  • "yes|no" accepts either the complete string "yes" or the complete string "no".
  • "[A-Za-z0-9_]{1,20}" accepts between one and twenty basic letters, digits, or underscores.

These examples describe limited formats, not universal rules for real-world data. For example, email addresses and human names have more variation than a short pattern may account for. A regex can be appropriate for checking a specific format, but a simplistic expression should not be treated as proof that an address exists or that a name is valid.

Java String Escaping and Regex Escaping

When a regex is written inside a Java string literal, it passes through two interpreters: Java first processes the string literal, then the regex engine interprets the resulting text. As a result, a backslash often has to be written twice in Java source code.

For example, the regex token \d+ means one or more digits in Java’s regex syntax. To place that regex in a Java string, write "\\d+" in source code; Java turns the doubled backslash into one backslash before the regex engine sees it. A character class such as [0-9]+ is often easier to read and avoids this particular escaping issue.

The same issue applies to literal regex metacharacters. To match a literal period, the regex can use \., and the Java string literal for that regex is "\\.". Alternatively, "[.]" matches a period without a backslash. When a pattern looks unexpectedly complicated, check whether each backslash is intended for Java string syntax, regex syntax, or both.

matches() Compared with find() and lookingAt()

Choose the matching operation based on the question the program needs to answer. The three common Matcher methods have different scopes:

  • matches() asks whether the entire input region matches the pattern.
  • lookingAt() asks whether a match begins at the start of the input region; it need not consume the rest.
  • find() searches for the next matching part anywhere in the input region.

For example, to check whether a sentence contains a sequence of digits, a matcher can use find():

import java.util.regex.Matcher;
import java.util.regex.Pattern;

Pattern digits = Pattern.compile("[0-9]+");
Matcher matcher = digits.matcher("Order 583 is ready");
boolean containsDigits = matcher.find(); // true

By contrast, calling "Order 583 is ready".matches("[0-9]+") returns false, because the entire sentence is not digits. Calling matches() with ".*[0-9]+.*" can make that particular check succeed, but find() communicates the search intent more directly and avoids needing to design a wrapper pattern.

When to Use Pattern and Matcher

String.matches() is concise for a one-off full-string check. Internally, however, using it repeatedly with the same regex causes the pattern to be compiled again for each call. For a loop that checks many values against one pattern, compile a Pattern once and create a matcher for each value instead.

Pattern accountCode = Pattern.compile("[A-Z]{2}[0-9]{3}");

for (String value : values) {
    boolean valid = accountCode.matcher(value).matches();
    System.out.println(value + ": " + valid);
}

The same Pattern can be reused, while each Matcher is associated with a particular input. This also gives access to operations such as find(), captured groups, and match positions. For a single simple condition, the shorter string method is often clearer; for repeated checks or more involved regex work, the regex classes offer more control.

Patterns can also use inline flags. For example, "(?i)yes|no" enables case-insensitive matching for the alternatives, so strings such as "YES" can match. If the pattern is reused, flags can instead be supplied when compiling a Pattern. There is no separate flags parameter on String.matches().

Common Problems and Edge Cases

A frequent surprise is that an empty string does not match a pattern that requires at least one character. For example, "".matches("[0-9]+") is false because + means one or more. Replacing it with * allows zero or more digits, so "".matches("[0-9]*") is true. Whether an empty value should pass is a separate validation decision; a pattern that accepts it may need an additional non-empty check.

Another issue is assuming that . means every possible character, including line breaks. By default, the dot in Java regex does not match line terminators. A pattern such as ".*" can therefore behave differently than expected when the input contains a newline. If a pattern really needs dot to include line terminators, Java regex supports the DOTALL flag, which can be enabled inline with (?s) or through Pattern flags.

Character classes also have limits. [A-Za-z] covers the basic Latin letters, not every letter used in every language. For broader text handling, Java regex supports Unicode-related properties, but the right rule depends on the application’s definition of an acceptable character. Similarly, [0-9] intentionally means the ASCII digits zero through nine; it is not a general statement that every script’s numeric characters are accepted.

An invalid regex causes a PatternSyntaxException when the method tries to compile it. The pattern is not silently treated as plain text. If the goal is literal equality, use String.equals() rather than matches(); that avoids regex interpretation altogether. Also note that calling a method on a null string reference causes a NullPointerException, and passing a null regex is not a substitute for an empty pattern.

Choosing the Right Approach

Use String.matches() when all of these are true: the value is non-null, the check is a full-string regex test, and the regex is simple or used infrequently. Use equals() for exact literal equality, a Matcher search for a substring, and a precompiled Pattern when applying one regex repeatedly or using advanced matching features.

Before adding a regex to production code, test both valid and invalid examples. Include boundary cases such as an empty string, a value that is one character too long, unexpected whitespace, and a string with a newline if relevant. Tests should reflect the actual format requirements rather than merely confirming that a few typical examples pass.

Whitespace deserves particular attention. A pattern such as "[A-Z]{2}[0-9]{3}" does not permit leading or trailing spaces. If the application should ignore surrounding whitespace, trim the value deliberately before checking it or build that behavior into the accepted format. Do not silently broaden a pattern without deciding whether whitespace is meaningful data.

Frequently Asked Questions

Does String.matches() check for a substring?
No. It requires the complete string to match the regex. Use Matcher.find() to search for a matching part within a larger string.

Do I need to add ^ and $ to String.matches()?
Usually not. matches() already checks the complete input region, so a pattern such as [A-Z]+ cannot match just a portion of a longer string.

Is the argument to matches() a regular expression?
Yes. Regex metacharacters have their usual meanings, so "." does not mean a literal period. Use "[.]" or escape the period appropriately when you need a literal dot.

Why does a regex backslash need to be doubled in Java?
Java processes the string literal before the regex engine receives it. For example, regex \d+ is written as "\\d+" in Java source so the regex engine receives one backslash followed by d+.

Is String.matches() case-sensitive?
Yes, by default. You can use an inline case-insensitive flag such as (?i) in the regex, or compile a Pattern with the appropriate flag when using the regex API.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.