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

Understanding find vs matches: Different Matching Goals

Learn the fundamental difference: find() searches for a pattern anywhere in the input, while matches() requires the entire input to match.

Understanding find vs matches: Different Matching Goals

You'll learn: The critical distinction between find() and matches() — two methods that look similar but serve fundamentally different matching purposes.

The Core Difference

When working with Matcher objects, find() and matches() answer different questions:

  • find() asks: "Does this pattern appear anywhere in the input string?"
  • matches() asks: "Does this pattern match the entire input string from start to finish?"

Think of it like searching for a word in a book. Using find() is like scanning pages to see if "Java" appears anywhere. Using matches() is like checking whether the entire book consists of only the word "Java" — nothing before it, nothing after it.

Practical Example

import java.util.regex.Pattern;
import java.util.regex.Matcher;

Pattern pattern = Pattern.compile("\\d{3}");
Matcher matcher1 = pattern.matcher("abc123def");
Matcher matcher2 = pattern.matcher("123");

// find() looks for the pattern anywhere
System.out.println(matcher1.find());    // true (found "123" inside)
System.out.println(matcher2.find());    // true (found "123")

matcher1.reset();
matcher2.reset();

// matches() requires the entire string to match
System.out.println(matcher1.matches()); // false ("abc123def" ≠ exactly three digits)
System.out.println(matcher2.matches()); // true ("123" = exactly three digits)

When to Use Each

Use find() when:

  • Searching for patterns embedded in larger text
  • Extracting data from logs, documents, or user input

Use matches() when:

  • Validating complete input (email addresses, phone numbers, IDs)
  • Ensuring strings conform to a specific format

Key Takeaway: find() searches for your pattern as a substring anywhere in the input, while matches() requires the entire input to match your pattern exactly — choose based on whether you're finding or validating.