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());
}
}- Expected output: TASK 42 false
- 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