Introduction to Pattern and Matcher
What you'll learn: How Java's regex API uses Pattern to compile regular expressions and Matcher to apply them to text.
The Two-Step Regex Process
Java's regular expressions API revolves around two key classes: Pattern and Matcher. Think of Pattern as a compiled recipe or blueprint for a search operation, while Matcher is the tool that actually performs the search on specific text.
Pattern takes a regular expression string (like "\\d+" for one or more digits) and compiles it into an optimized, reusable form. This compilation step is separate because it's relatively expensive—you don't want to repeat it every time you search.
Matcher applies that compiled pattern to a particular input sequence (a CharSequence, which includes String). The Matcher object keeps track of the search state, knows where matches were found, and can perform operations like finding, replacing, or extracting matched text.
Why Two Classes?
This separation provides flexibility and performance. You compile a Pattern once and reuse it across many different input strings. Each input gets its own Matcher instance, which maintains independent search state. This design is especially valuable when you need to apply the same regex to thousands of strings—compile once, match many times.
The Basic Workflow
- Create a
Patternby compiling a regex string - Obtain a
Matcherby callingpattern.matcher(inputText) - Use
Matchermethods to find matches, extract groups, or perform replacements
The Pattern class is thread-safe and immutable after creation. The Matcher is not thread-safe (it maintains mutable state), so each thread needs its own instance.
Key Takeaway: Pattern compiles and optimizes regex strings for reuse; Matcher applies that pattern to specific input sequences and tracks match state.