Codectionary / Developer documentation / Java

Regular Expressions with Pattern

Pattern compiles a reusable regex while Matcher holds the state of a particular search. matches validates the entire input; find searches for the next matching region. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

Pattern.compile(regex).matcher(text).matches()

Examples

Regular Expressions with Pattern

Save as Main.java and run with a Java 17+ JDK: java Main.java.

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

public class Main {
  public static void main(String[] args) throws Exception {
    Pattern pattern = Pattern.compile("([A-Z]+)-([0-9]{3})");
    Matcher match = pattern.matcher("TASK-042");
    if (match.matches()) {
      System.out.println(match.group(1));
      System.out.println(Integer.parseInt(match.group(2)));
    }
    System.out.println(pattern.matcher("TASK-042-extra").matches());
  }
}
  1. Expected output: TASK 42 false
  2. Capture groups are available after a successful match. The final input is rejected because it has trailing characters.

Best practices

  • Reuse Pattern but create separate Matcher instances for concurrent operations.
  • Avoid ambiguous nested repetition on untrusted long inputs.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading