Compiling Patterns
Pattern.compile and Matcher.
Compiling Patterns is a free Java Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Pattern and Matcher Pair
Java regex lives in java.util.regex. A Pattern is a compiled regular expression; a Matcher applies that pattern to a specific input.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("abc123");
System.out.println(m.find());
}
}Compiling Once, Reusing Often
Pattern.compile is relatively expensive. Compile a pattern once and reuse it across many inputs rather than recompiling in a loop.
import java.util.regex.Pattern;
public class Main {
static final Pattern DIGITS = Pattern.compile("\\d+");
public static void main(String[] args) {
System.out.println(DIGITS.matcher("a1").find());
System.out.println(DIGITS.matcher("bb").find());
}
}Escaping Backslashes in Java
Regex tokens like \d need a backslash, but Java strings also use backslash for escapes. So in source code you write \\d to mean the regex \d.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern word = Pattern.compile("\\w+");
System.out.println(word.matcher("hello").matches());
}
}Creating a Matcher
pattern.matcher(input) binds the pattern to an input string and returns a fresh Matcher that tracks position.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("the cat sat");
System.out.println(m.find());
}
}Matchers Are Stateful
A Matcher holds mutable state (current position, last match). Create a new matcher per input; do not share one across threads.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d");
Matcher m = p.matcher("a1b2");
System.out.println(m.find());
System.out.println(m.find());
}
}Case-Insensitive Flag
Pass flags as a second argument to compile. Pattern.CASE_INSENSITIVE ignores letter case.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern p = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
System.out.println(p.matcher("I love JAVA").find());
}
}Combining Flags
Combine flags with the bitwise OR operator. Here we add MULTILINE so anchors match at each line.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern p = Pattern.compile("^a", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher m = p.matcher("apple\nApricot");
int count = 0;
while (m.find()) count++;
System.out.println(count);
}
}The Static matches Shortcut
Pattern.matches(regex, input) is a one-shot helper that compiles and tests in a single call. Convenient, but it recompiles every time.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println(Pattern.matches("\\d{3}", "123"));
System.out.println(Pattern.matches("\\d{3}", "12"));
}
}Splitting with a Pattern
A compiled Pattern can split strings via split, reusing the same compiled regex efficiently.
import java.util.Arrays;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern comma = Pattern.compile("\\s*,\\s*");
String[] parts = comma.split("a, b ,c, d");
System.out.println(Arrays.toString(parts));
}
}Inspecting the Pattern
pattern() returns the original regex string and flags() returns the active flags as an int.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);
System.out.println(p.pattern());
System.out.println(p.flags());
}
}Invalid Patterns Throw
A malformed regex throws PatternSyntaxException at compile time, letting you catch errors early.
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class Main {
public static void main(String[] args) {
try {
Pattern.compile("[unclosed");
} catch (PatternSyntaxException e) {
System.out.println("Invalid regex");
}
}
}Quick Check
Why should you compile a frequently used regex into a static Pattern field?
Recap
You compiled patterns:
Pattern.compilebuilds a reusable, immutable, thread-safe pattern;matcherbinds it to an input.- Escape regex backslashes as
\\in Java source. - Flags like
CASE_INSENSITIVEandMULTILINEcombine with bitwise OR. Matcheris stateful, so create one per input.
Frequently asked questions
Is the “Compiling Patterns” lesson free?
Yes — the full text of “Compiling Patterns” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Compiling Patterns”?
Pattern.compile and Matcher. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Compiling Patterns” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Compiling Patterns
- Finding and Matching
- Capturing Groups
- Replacing with Regex