Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

`Matcher.matches()`: Match the entire region in Java

`Matcher.matches()` tests a regular expression against the entire current region, not just a substring. By default, the region covers the whole input.

Version: Java SE 21

Syntax

public boolean matches()

Matcher.matches() is a no-argument instance method of java.util.regex.Matcher. Compile the regular expression with Pattern.compile(regex), create a Matcher with pattern.matcher(input), and call matcher.matches(). It returns true only if the pattern matches the entire current region; otherwise it returns false.

By default, the region covers the whole input. Use region(start, end) to set its bounds: start is inclusive and end is exclusive. After setting those bounds, matches() requires the entire selected region to match, not the whole original input. You don't need to add ^ and $ just to require a full-region match.

Use lookingAt() if a match at the beginning of the region is enough, or find() to search for the next matching subsequence in the region. After matches() returns true, group() gives you the matched text, and start() and end() give you its inclusive start and exclusive end indices in the input. After false, those three methods throw IllegalStateException if called before another successful match.

Examples

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Pattern fourDigits = Pattern.compile("[0-9]{4}");
        String input = "id=1234!";

        System.out.println(fourDigits.matcher(input).matches());
        System.out.println(fourDigits.matcher(input).find());
        System.out.println(fourDigits.matcher("1234!").lookingAt());

        Matcher selected = fourDigits.matcher(input).region(3, 7);
        boolean matched = selected.matches();
        System.out.println(matched);
        if (matched) {
            System.out.println(selected.group());
        }
    }
}

Result

false
true
true
true
1234

The pattern `[0-9]{4}` requires exactly four ASCII digits. The whole string `id=1234!` does not match, but `find()` locates `1234`. On `1234!`, `lookingAt()` matches the prefix. Region `[3, 7)` of `id=1234!` contains only `1234`, so `matches()` returns `true` and `group()` returns `1234`.

Related lessons

  • Java · Lesson 70 · Basic · Version: 2

Sources