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}"));true
false
kodasstores the text JAVA-2026.[A-Z]{4}requires exactly four uppercase Latin letters.- The pattern's hyphen must match the text's hyphen.
\d{4}requires exactly four digits, so the first result istrue.- Java-26 fails the case and digit-count requirements, giving
false.
Method syntax
public boolean matches(String regex)
| Part | Meaning |
|---|---|
| Calling object | The String text |
| Parameter | regex – regular expression |
| Return type | boolean |
true | The entire string matches |
false | The entire string does not match |
| Possible errors | PatternSyntaxException 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);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.*"));false
true
- The pattern
Javadescribes only a four-letter string. - The full sentence is Mokausi Java, so the first comparison returns
false. - The regex fragment
.*means “zero or more of any character”. .*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
| Element | Meaning |
|---|---|
. | Any character except certain line terminators |
\d | Digit |
\s | Whitespace 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}"));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ą");
}Vartotojo vardas tinkamas
[A-Za-z]requires the first character to be a Latin letter.[A-Za-z0-9_]allows letters, digits and underscores in later positions.{2,15}requires another 2–15 characters, giving a total length of 3–16.- 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"));true
false
- An unescaped
.is a special regex element, sojava.txtalso matches javaXtxt. - To match a literal dot, write it at regex level as
\.. - In a Java literal, escape each backslash again, producing
"java\\.txt". - 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"));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.*"));false
true
true
| The method | What 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(""));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"));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());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));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 throwsPatternSyntaxException. - Overlooking that regex is case-sensitive by default.
- Repeatedly passing the same complex regex to
matches()instead of reusing a compiledPattern. - Passing a
nullregex or calling the method through anull.
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().