0
0
JavaHow-ToBeginner · 3 min read

How to Find All Matches in String Java - Simple Guide

In Java, you can find all matches in a string by using Pattern and Matcher classes. Compile a regex with Pattern.compile(), create a Matcher with pattern.matcher(input), then use matcher.find() in a loop to get each match.
📐

Syntax

To find all matches in a string, use these steps:

  • Pattern.compile(regex): Creates a pattern object from your regular expression.
  • pattern.matcher(inputString): Creates a matcher to search the input string.
  • matcher.find(): Finds the next match each time it is called, returning true if found.
  • matcher.group(): Returns the matched substring.
java
Pattern pattern = Pattern.compile("your-regex");
Matcher matcher = pattern.matcher("your input string");
while (matcher.find()) {
    String match = matcher.group();
    // process match
}
💻

Example

This example finds all words starting with a capital letter in a sentence and prints them one by one.

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

public class FindAllMatches {
    public static void main(String[] args) {
        String text = "Java is Fun. Learning Java is rewarding.";
        Pattern pattern = Pattern.compile("\\b[A-Z][a-z]*\\b");
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}
Output
Java Fun Learning Java
⚠️

Common Pitfalls

Common mistakes when finding matches include:

  • Using matcher.group() before calling matcher.find(), which causes errors.
  • Not looping with matcher.find() and only getting the first match.
  • Using incorrect regex patterns that do not match the intended text.

Always call matcher.find() in a loop and then get the match with matcher.group().

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

public class WrongWay {
    public static void main(String[] args) {
        String text = "Test 123 Test 456";
        Pattern pattern = Pattern.compile("Test");
        Matcher matcher = pattern.matcher(text);

        // Wrong: calling group() before find()
        // System.out.println(matcher.group()); // Throws IllegalStateException

        // Right way:
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}
Output
Test Test
📊

Quick Reference

Remember these key points when finding all matches in Java strings:

  • Use Pattern.compile() to create a regex pattern.
  • Create a Matcher from the pattern and input string.
  • Loop with matcher.find() to get each match.
  • Use matcher.group() to access the matched text.

Key Takeaways

Use Pattern and Matcher classes to find all matches in a string.
Call matcher.find() repeatedly in a loop to get each match.
Access the matched text with matcher.group() after find().
Avoid calling matcher.group() before matcher.find() to prevent errors.
Write correct regex patterns to match the desired text.