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

The find() Loop: Iterating Through Multiple Matches

Discover how to call find() repeatedly in a loop to locate all occurrences of a pattern within a single input string.

The find() Loop: Iterating Through Multiple Matches

What you'll learn: How to use find() repeatedly in a loop to discover every occurrence of a pattern in a string, not just the first one.

The Core Idea

You've already seen that find() searches for a pattern anywhere in your input string and returns true when it finds a match. Here's the powerful part: each call to find() advances the matcher to search from where the last match ended. This means you can call find() in a loop to walk through all matches in the string, one at a time.

Think of it like scanning a document with a highlighter. Each time you find your search term, you highlight it and then continue scanning from that point forward—you don't restart from the beginning.

How It Works in Practice

Pattern pattern = Pattern.compile("\\d+"); // matches one or more digits
Matcher matcher = pattern.matcher("Order 123 costs $45, item 789 ships tomorrow");

while (matcher.find()) {
    System.out.println("Found: " + matcher.group() + 
                       " at position " + matcher.start());
}

Output:

Found: 123 at position 6
Found: 45 at position 18
Found: 789 at position 26

Each time through the loop, find() locates the next number in the string. The matcher automatically maintains its position internally, so you don't need to manage offsets manually.

Common Pattern: Extract All Matches

Pattern pattern = Pattern.compile("[A-Z]{3}");
Matcher matcher = pattern.matcher("Codes: ABC, DEF, GHI");

while (matcher.find()) {
    System.out.println(matcher.group());
}
// Prints: ABC, DEF, GHI (on separate lines)

Key Takeaway: Call find() in a while loop to iterate through all pattern matches in a string—the matcher automatically advances after each successful find, letting you process every occurrence sequentially.