CKTIS / Java
Pattern.compile — compile a regular expression
Compile a regular expression into a `Pattern` object, then reuse that pattern to check more than one input.
Version: Java SE 21
Syntax
import java.util.regex.Pattern;
// Static method signatures in java.util.regex.Pattern:
public static Pattern compile(String regex)
public static Pattern compile(String regex, int flags)In Java SE 21, Pattern.compile is a static method of java.util.regex.Pattern. It takes a regular expression as a String and returns a compiled Pattern. Compilation itself does not test any input text.
Pattern.compile(regex) takes no separate flags argument, but the expression can still contain an embedded flag such as (?i). The Pattern.compile(regex, flags) overload takes an int bit mask. Use | to combine flags, for example Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE for Unicode-aware case-insensitive matching.
Invalid regex syntax throws the unchecked exception PatternSyntaxException when the pattern is compiled. The flags overload throws IllegalArgumentException if the mask sets bits that do not correspond to defined flags.
pattern.matcher(input) creates a Matcher for the given input. Its matches() method tests the entire current region, which is the whole input by default. Use find() to look for a matching substring instead. For repeated checks, reuse the immutable Pattern, which is safe to share across threads. A Matcher holds matching state and is not safe to use concurrently.
Examples
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern[] patterns = {
Pattern.compile("[A-Z]{2}[0-9]{2}"),
Pattern.compile("[0-9]+"),
Pattern.compile("[A-Z]+"),
Pattern.compile("[A-Z0-9]+"),
Pattern.compile("AB.*")
};
System.out.println("Pattern | AB12 | 123");
for (Pattern pattern : patterns) {
System.out.println(pattern.pattern() + " | "
+ pattern.matcher("AB12").matches() + " | "
+ pattern.matcher("123").matches());
}
}
}Result
Pattern | AB12 | 123
[A-Z]{2}[0-9]{2} | true | false
[0-9]+ | false | true
[A-Z]+ | false | false
[A-Z0-9]+ | true | true
AB.* | true | false
The program compiles five patterns with no flags and checks each one against `AB12` and `123`. Notice that `[A-Z]+` does not match `AB12`: the letters `AB` fit the pattern, but `matches()` requires the whole input to match.
Related lessons
- Java · Lesson 70 · Basic · Version: 2