Course contentsShow
← Java
Lesson 2245 of 2,87044. Regular ExpressionsFree lesson

Compiling a Pattern

Using Pattern.compile() to create reusable Pattern objects from regex strings for efficient matching.

Compiling a Pattern

You'll learn how to turn regex strings into reusable Pattern objects for efficient matching.

When you need to use the same regular expression multiple times, you don't want to reparse it every time. That's where Pattern.compile() comes in—it converts your regex string into a compiled Pattern object that Java can reuse efficiently.

What Pattern.compile() Does

Think of Pattern.compile() like compiling source code into bytecode. You write your regex once as a String (like "\\d{3}-\\d{2}-\\d{4}"), and compile() analyzes it, validates it, and builds an optimized internal representation. That compiled Pattern object is ready to match against many input strings without reparsing the regex each time.

import java.util.regex.Pattern;

// Compile the pattern once
Pattern ssnPattern = Pattern.compile("\\d{3}-\\d{2}-\\d{4}");

// Now you can reuse it efficiently
String input1 = "123-45-6789";
String input2 = "987-65-4321";

// Use the same compiled pattern multiple times
boolean match1 = ssnPattern.matcher(input1).matches();
boolean match2 = ssnPattern.matcher(input2).matches();

Why Compile?

Parsing and optimizing a regex takes time. If you're checking hundreds or thousands of strings against the same pattern, compiling once and reusing saves significant CPU cycles. It's the difference between translating the same sentence from English to French every single time versus translating it once and keeping the French version handy.

Store your compiled Pattern as a constant when possible—often as a static final field—so the entire application shares one compiled version.

Key Takeaway: Use Pattern.compile() to create reusable, optimized Pattern objects from regex strings, dramatically improving performance when matching the same pattern repeatedly.