Java String.matches
Test whether the entire string matches a regular expression.
A simple example
String.matches
- Start with "12" and the pattern ^[0-9]+$
- Do this Match the whole string
- Result Match
class Main {
public static void main(String[] args) throws Exception {
System.out.println("12".matches("^[0-9]+$"));
}
}
true
Syntax
public boolean matches(String regex)
JDK 21 method signatures (1)
public boolean matches(String regex)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaValidate a classroom seat code
A classroom scanner expects a seat identifier in a specific format. Validate the whole field so an otherwise valid prefix cannot admit stray characters at the end.
class Main {
public static void main(String[] args) throws Exception {
String seat = "B12";
System.out.println(seat.matches("[A-Z][0-9]{2}"));
}
}
true
One capital letter and exactly two digits occupy the whole field.
Reject extra text after a parcel number
A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.
class Main {
public static void main(String[] args) throws Exception {
String input = "482 paid";
System.out.println(input.matches("[0-9]+"));
}
}
false
The space and letters prevent a full-field match.
Validate a sample label
A lab assistant scans a four-character sample code. The form accepts exactly two capital ASCII letters followed by two digits. Does the complete entry meet that rule?
What to watch for
For a substring search use Matcher.find. Reuse a compiled Pattern for repeated checks.