Creating a Matcher from a Pattern
What you'll learn: How to create a Matcher instance from a compiled Pattern to search and manipulate specific text.
The Connection Between Pattern and Matcher
Once you've compiled a Pattern (your reusable regex blueprint), you need to apply it to actual text. That's where the Matcher comes in. Think of the Pattern as a cookie cutter—it defines the shape—and the Matcher as pressing that cutter into a specific batch of dough. The pattern stays the same, but each matcher works on different input.
Creating the Matcher
You create a Matcher by calling the matcher() method on your Pattern instance, passing in the CharSequence (typically a String) you want to search:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Order 123 has 45 items");
The matcher() method returns a new Matcher object configured to search through "Order 123 has 45 items" using the compiled regex pattern \\d+ (one or more digits).
Why Separate Pattern and Matcher?
This two-step design is intentional. The Pattern is expensive to compile but reusable. You compile it once, then create multiple Matcher instances for different input strings:
Pattern emailPattern = Pattern.compile("[a-z]+@[a-z]+\\.[a-z]+");
Matcher matcher1 = emailPattern.matcher("Contact: alice@example.com");
Matcher matcher2 = emailPattern.matcher("Email: bob@test.org");
Each Matcher operates independently on its own input, but they share the same compiled pattern, saving compilation overhead.
Key Takeaway: Call pattern.matcher(input) to create a Matcher instance that applies your compiled pattern to a specific CharSequence, enabling you to perform search and manipulation operations on that text.