Library contents

Java String.matches

Test whether the entire string matches a regular expression.

A simple example

String.matches

  1. Start with "12" and the pattern ^[0-9]+$
  2. Do this Match the whole string
  3. Result Match
Both characters are digits, so the pattern covers the text from beginning to end.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("12".matches("^[0-9]+$"));
    }
}
Output
true

Syntax

Java 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.java

Validate 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.

From the programString seat = "B12"
Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String seat = "B12";
        System.out.println(seat.matches("[A-Z][0-9]{2}"));
    }
}
Output
true

One capital letter and exactly two digits occupy the whole field.

Advertisements

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.

From the programString input = "482 paid"
Resultfalse
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String input = "482 paid";
        System.out.println(input.matches("[0-9]+"));
    }
}
Output
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?

GivenPH07
Worked resultAccept

What to watch for

For a substring search use Matcher.find. Reuse a compiled Pattern for repeated checks.

Documentation for String.matches