Menu
Coddy logo textTech

Pattern Matching with Regex

Part of the Logic & Flow section of Coddy's Java journey — lesson 47 of 59.

The Pattern and Matcher classes provide powerful tools for regex operations in Java. First, let's understand how to use them:

Create a pattern using Pattern.compile():

Pattern pattern = Pattern.compile("cat");
// Creates a pattern to find "cat"

Create a matcher for your text:

String text = "The cat and dog";
Matcher matcher = pattern.matcher(text);
// Creates a matcher for the text

Now you can find matches using matcher.find():

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

After executing the above code, the output is: Found at: 4

Understanding the methods:

  • <b>matcher.find()</b> - Searches for the next occurrence of the pattern in the text
    • Returns true if a match is found
    • Returns false if no more matches exist
    • This is why we use it in a while loop - to find all occurrences
  • <b>matcher.start()</b> - Returns the starting index (position) of the last match found by find()
    • In our example, "cat" starts at index 4 in "The cat and dog"
    • Must be called after a successful find()

Example with multiple matches:

Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher("cat and cat");

while (matcher.find()) {
   System.out.println("Found at: " + matcher.start());
}
// Output:
// Found at: 0
// Found at: 8
challenge icon

Challenge

Easy

Create a method named findWords that takes two arguments:

  1. A String (text) to search in
  2. A String (word) to find

The method should:

  1. Use Pattern and Matcher to find all occurrences of the word
  2. Return a string containing the positions where the word was found
  3. Positions should be separated by spaces

Return messages should be:

  • If any input is null: return "Invalid input"
  • If word not found: return "Not found"
  • If found: return positions (e.g., "4 10 15")

Cheat sheet

The Pattern and Matcher classes provide powerful tools for regex operations in Java.

Create a pattern using Pattern.compile():

Pattern pattern = Pattern.compile("cat");
// Creates a pattern to find "cat"

Create a matcher for your text:

String text = "The cat and dog";
Matcher matcher = pattern.matcher(text);
// Creates a matcher for the text

Find matches using matcher.find():

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

Key methods:

  • <b>matcher.find()</b> - Searches for the next occurrence of the pattern
    • Returns true if found, false if no more matches
    • Use in a loop to find all occurrences
  • <b>matcher.start()</b> - Returns the starting index of the last match found
    • Call after a successful find()

Try it yourself

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

public class Main {
    public static String findWords(String text, String word) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        String word = scanner.nextLine();
        
        if (text.equals("null")) text = null;
        if (word.equals("null")) word = null;
        
        System.out.println(findWords(text, word));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow