STRING INSTANCE METHODS

Java String matches() method

matches() checks whether an entire String string matches a specified regular expression, or regex. It returns truewhen the entire text matches the pattern and falseotherwise.

Checking a text format

String kodas = "JAVA-2026";

System.out.println(kodas.matches("[A-Z]{4}-\\d{4}"));
System.out.println("Java-26".matches("[A-Z]{4}-\\d{4}"));
Console output

true
false

  1. kodas stores the text JAVA-2026.
  2. [A-Z]{4} requires exactly four uppercase Latin letters.
  3. The pattern's hyphen must match the text's hyphen.
  4. \d{4} requires exactly four digits, so the first result is true.
  5. Java-26 fails the case and digit-count requirements, giving false.

Method syntax

public boolean matches(String regex)

Parts of the matches() method
PartMeaning
Calling objectThe String text
Parameterregex – regular expression
Return typeboolean
trueThe entire string matches
falseThe entire string does not match
Possible errorsPatternSyntaxException for an invalid regex or NullPointerException for null

Invocation tekstas.matches(regex) produces the same result as Pattern.matches(regex, tekstas).

Why is matches() an instance method?

The regex is applied to specific text, so the method is called on the tested String object:

boolean tinkamas = tekstas.matches("[A-Za-z]+\\d+");

String tekstas = "Java123";

boolean tinkamas = tekstas.matches("[A-Za-z]+\\d+");

System.out.println(tinkamas);
Console output

true

On the left, tekstas is the value being tested, and the regex is the argument. We therefore do not write String.matches(...) : a static call would not know which text to check.

matches() checks the whole string

String sakinys = "Mokausi Java";

System.out.println(sakinys.matches("Java"));
System.out.println(sakinys.matches(".*Java.*"));
Console output

false
true

  1. The pattern Java describes only a four-letter string.
  2. The full sentence is Mokausi Java, so the first comparison returns false.
  3. The regex fragment .* means “zero or more of any character”.
  4. .*Java.* allows text before and after Java, so the whole sentence matches.

For a regex search within text rather than a whole-string match, use Pattern, Matcher and find().

Common regex elements

Meanings of common regex elements
ElementMeaning
.Any character except certain line terminators
\dDigit
\sWhitespace character
[A-Z]One uppercase Latin letter
+One or more repetitions of the previous element
*Zero or more repetitions
?Zero or one repetition
{n}Exactly n repetitions
{n,m}From n to m repetitions

Checking digit count

String pin = "4827";

System.out.println(pin.matches("\\d{4}"));
System.out.println("48A7".matches("\\d{4}"));
Console output

true
false

The regex \d{4} means exactly four digits. A Java string literal needs a doubled backslash, so the code contains "\\d{4}". A value containing the letter A does not match this pattern.

Practical example: username validation

String vartotojoVardas = "java_quest7";

boolean tinkamas = vartotojoVardas.matches("[A-Za-z][A-Za-z0-9_]{2,15}");

if (tinkamas) {
  System.out.println("Vartotojo vardas tinkamas");
} else {
  System.out.println("Patikrink vartotojo vardą");
}
Console output

Vartotojo vardas tinkamas

  1. [A-Za-z] requires the first character to be a Latin letter.
  2. [A-Za-z0-9_] allows letters, digits and underscores in later positions.
  3. {2,15} requires another 2–15 characters, giving a total length of 3–16.
  4. java_quest7 satisfies all these rules, so a success message is printed.

In a real system, regex is only part of validation: reserved names, uniqueness and business rules may need separate checks.

A regex dot means any character

String failas = "javaXtxt";

System.out.println(failas.matches("java.txt"));
System.out.println(failas.matches("java\\.txt"));
Console output

true
false

  1. An unescaped . is a special regex element, so java.txt also matches javaXtxt.
  2. To match a literal dot, write it at regex level as \..
  3. In a Java literal, escape each backslash again, producing "java\\.txt".
  4. javaXtxt has no actual dot, so the second result is false.

Letter case and the (?i) flag

String tekstas = "JavaQuest";

System.out.println(tekstas.matches("javaquest"));
System.out.println(tekstas.matches("(?i)javaquest"));
Console output

false
true

Regex is case-sensitive by default. The embedded flag (?i) enables case-insensitive matching for this expression, so the second comparison matches.

Differences between matches(), equals() and contains()

String tekstas = "Mokausi Java";

System.out.println(tekstas.equals("Java"));
System.out.println(tekstas.contains("Java"));
System.out.println(tekstas.matches(".*Java.*"));
Console output

false
true
true

Choosing a text-checking method
The methodWhat does it check?
equals()Whether the full text exactly equals another string
contains()Whether text contains a specific literal sequence
matches()Whether the whole text matches a regex format

Checking empty text

String tuscias = "";

System.out.println(tuscias.matches(""));
System.out.println(tuscias.matches(".*"));
System.out.println("Java".matches(""));
Console output

true
true
false

An empty regex matches only empty text. The expression .* allows zero characters, so it also matches "". Nonempty text, Java , does not match an empty pattern.

Invalid regex causes PatternSyntaxException

String tekstas = "Java";

System.out.println(tekstas.matches("[A-Z"));
Result

PatternSyntaxException

The pattern starts a character class with [A-Zbut does not close it with ]. Java cannot interpret the expression and throws PatternSyntaxExceptionrather than returning false.

Compile frequently used regex once

import java.util.regex.Pattern;

Pattern kodas = Pattern.compile("[A-Z]{2}-\\d{3}");

System.out.println(kodas.matcher("LT-123").matches());
System.out.println(kodas.matcher("EE-456").matches());
Console output

true
true

Each String.matches() must interpret the regex on each call. When one pattern is applied to many values, compile it once using Pattern.compile(), then create a matcher for each string.

The regex cannot be null

String tekstas = "Java";
String regex = null;

System.out.println(tekstas.matches(regex));
Result

NullPointerException

If the regex argument is null, Java has no expression to check the text against and throws NullPointerException. The method also cannot be called on a null string reference.

Common mistakes

  • Expecting matches() to find partial matches although it checks the whole string.
  • Forgetting to double backslashes in Java literals, for example writing "\d+" instead of "\\d+".
  • Treating special regex symbols, such as ., *, + or ?, as ordinary characters.
  • Expecting an invalid regex to return falsewhen it throws PatternSyntaxException.
  • Overlooking that regex is case-sensitive by default.
  • Repeatedly passing the same complex regex to matches()instead of reusing a compiled Pattern.
  • Passing a null regex or calling the method through a null.

When should you use matches()?

Use matches()when the entire text must follow a clear format: an identifier, code, username, phone number or other structured input. For simple equality, use equals(); for a literal substring search, use contains(); for a regex search within text, use Matcher.find().