The find() Method: Substring Searching
You'll learn how to search for pattern matches anywhere within a string, not just at the beginning or end.
The Core Idea
While matches() requires your entire string to match the pattern, find() takes a different approach: it searches through the input string to locate the next occurrence of the pattern anywhere within it. Think of it like using Ctrl+F in a text editor—you're looking for a substring match, not demanding that the entire document be exactly your search term.
When you call find() on a Matcher object, it scans forward from its current position (or the beginning, on first call) and returns true if it finds a match, false otherwise. Each successful call advances the matcher's internal position, so calling find() repeatedly lets you discover multiple matches in sequence.
How It Works
import java.util.regex.*;
Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher("The cat and the catalog");
// First call finds "cat" at position 4
boolean found = matcher.find(); // true
// Second call finds "cat" in "catalog" at position 19
found = matcher.find(); // true
// Third call finds nothing
found = matcher.find(); // false
You can also use find() in a loop to process all matches:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("I have 3 cats and 12 dogs");
while (m.find()) {
// Processes "3", then "12"
}
Key Takeaway: Use find() to search for pattern occurrences anywhere within your input string, with each call advancing to the next match—perfect for extracting multiple substrings that match a pattern.