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

Using find() to Locate Patterns Within Strings

Explore how find() scans the input string and returns true when it locates the pattern anywhere, positioning the matcher at the match.

Using find() to Locate Patterns Within Strings

You'll learn how find() scans through a string to locate your pattern anywhere inside it, not just at the beginning or as a complete match.

The Core Idea

Think of find() as a search spotlight that moves across your input string, looking for your pattern anywhere within the text. Unlike matches() which demands the entire string follow your pattern, or lookingAt() which only checks the start, find() is like using Ctrl+F in a text editor—it hunts through the entire string until it spots your pattern.

When find() discovers a match, it:

  1. Returns true
  2. Positions the Matcher at that match location
  3. Lets you access match details with start(), end(), and group()

If you call find() again on the same Matcher, it continues searching from where it left off, potentially finding multiple matches in one string.

How It Works

Pattern pattern = Pattern.compile("Java");
Matcher matcher = pattern.matcher("I love Java and Java loves me");

if (matcher.find()) {
    System.out.println("Found at index: " + matcher.start());  // 7
    System.out.println("Matched: " + matcher.group());         // Java
}

if (matcher.find()) {
    System.out.println("Found again at: " + matcher.start());  // 16
}

Notice how the second find() call picks up where the first left off, discovering the second "Java" in the string.

The Scanning Behavior

Each successful find() advances the Matcher's internal position. This makes it perfect for processing all occurrences of a pattern in text—just keep calling find() in a loop until it returns false.

Key Takeaway: find() scans the input string for your pattern anywhere within it, returning true and positioning the matcher at each successive match, making it ideal for locating patterns embedded in larger text.