Pattern.compile()
Compiles a regular expression into a Pattern object that can be reused many times.
Available since: Java 1.4
Syntax
static Pattern compile(String regex, int flags)Parameters
| Parameter | Type | Description |
|---|---|---|
| regex | String | The regular expression. A backslash is written twice in a Java string. |
| flags | int | Flags such as Pattern.CASE_INSENSITIVE. Optional. |
Return value
PatternThe compiled pattern.
Examples
A pattern is created once and used for many strings:
void main() {
Pattern zip = Pattern.compile("\\d{5}");
for (String s : List.of("10115", "1011", "abcde")) {
IO.println(s + " " + zip.matcher(s).matches());
}
}Output:
10115 true
1011 false
abcde falseA case-insensitive flag, and splitting a string:
void main() {
Pattern java = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
IO.println(java.matcher("I like JAVA").find());
Pattern sep = Pattern.compile("\\s*[,;]\\s*");
IO.println(Arrays.toString(sep.split("a , b;c ;d")));
}Output:
true
[a, b, c, d]Notes
Compiling a pattern is expensive. String.matches(), replaceAll() and split() compile the expression on every call, so in a loop or a frequently called method keep the pattern in a private static final Pattern field. A Pattern is immutable and thread-safe.
A mistake in the expression causes PatternSyntaxException. To search for text literally, without special characters, wrap it in Pattern.quote().
See also
- Pattern.matcher() — Creates a Matcher that searches for the pattern in a specific string.
- Matcher.find() — Searches for the next match of the pattern anywhere in the string.
- String.matches() — Checks whether the whole string matches a regular expression.
- String.replaceAll() — Replaces every match of a regular expression.
Related recipes
In the tutorial
- Regular expressions — Regular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.