Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Pattern — a compiled regular expression

java.util.regex.Pattern stores a compiled regular expression. Pattern.compile creates the pattern, and Pattern.matcher creates a Matcher for checking an entire input or searching for matching subsequences.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
boolean wholeInputMatches = matcher.matches();
boolean nextMatchFound = matcher.find();

java.util.regex.Pattern represents a compiled regular expression. Pattern.compile(regex) creates a pattern, and Pattern.matcher(input) creates a Matcher for the supplied text. The Matcher performs matching; creating the pattern alone does not.

Regular expression syntax describes acceptable text. In ID-(\d{3}), ID- is literal, \d means an ASCII digit by default, {3} requires three repetitions, and parentheses form a capturing group. Java string literals require doubled backslashes: "ID-(\\d{3})".

matches() checks the entire matching region, which defaults to the entire input. find() searches for the next matching subsequence. After a successful match, group(1) returns the first group's text; here it is 042, still as text.

Compile a reused pattern once. Pattern is immutable and safe to share between threads; Matcher is not. Invalid syntax causes PatternSyntaxException. When text should be treated literally rather than as regex syntax, use Pattern.quote(text).

Examples

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

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("ID-(\\d{3})");
        System.out.println(pattern.matcher("ID-042").matches());
        System.out.println(pattern.matcher("Order ID-042").matches());

        Matcher matcher = pattern.matcher("Order ID-042");
        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

Result

true
false
042

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources