Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท java.lang

Java String.matches() method

Reference for Java String.matches(): test whether a whole string fits a regular expression, why partial matches fail, and when to use Pattern instead.

matches() checks whether the entire string matches a regular expression. It returns true or false; there are no groups to read and nothing to iterate. It is the shortest way to validate that a value has the right shape, such as "digits only" or "looks like a postal code".

The word that trips people up is entire. "abc123".matches("\\d+") is false, because the letters at the start are not digits. The method behaves as if the pattern were anchored at both ends.

Java
boolean ok = "2024-05-17".matches("\\d{4}-\\d{2}-\\d{2}"); // true

Try it

Java Whole-string matching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Invalid patterns and reuse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public boolean matches(String regex)

This is shorthand for Pattern.matches(regex, this), that is, Pattern.compile(regex).matcher(this).matches().

Name Description
regex The regular expression, written in Java regex syntax. Remember to double the backslashes in a string literal.

Returns: true if the whole string matches, otherwise false.

Throws: PatternSyntaxException if the expression is invalid. NullPointerException if regex is null.

Usage notes

  • Whole string, not a search. To find a pattern anywhere, use Matcher.find() or wrap the pattern in .*...*. Remember . does not cross line breaks unless you add (?s).
  • Backslashes are doubled in literals: the regex \d is written "\\d". Text blocks and raw strings need the same care.
  • Compiled on every call. In a loop or a hot path, precompile with Pattern.compile() and reuse the Pattern (it is thread-safe).
  • Case-insensitive matches use the flag (?i) at the start of the pattern or Pattern.CASE_INSENSITIVE.
  • Catastrophic backtracking. Nested quantifiers like (a+)+b can take exponential time on crafted input. Never run user-supplied patterns, and be careful with user-supplied text. See Regex pitfalls.
  • Validation, not parsing. Complicated formats such as email addresses or URLs are better handled by dedicated parsers (URI, InetAddress) than by one huge regex.
  • Other regex-powered string methods: split(), replaceAll() and replaceFirst().