Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
regexStringThe regular expression. A backslash is written twice in a Java string.
flagsintFlags 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 false

A 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

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.

Thanks for reading!

Donate to the site — we work hard for you.