java.util.Matcher

java.util.regex.Matcher is a class used to perform matching operations on text using a Pattern. It checks whether text matches a regular expression and can also find matching portions of text. Matcher is commonly used for validation, searching, extracting, and replacing text. It works closely with the Pattern class in the java.util.regex package.

Important Features:

  • Checks complete text using matches().
  • Searches for patterns using find().
  • Retrieves matched text using group().
  • Provides match positions using start() and end().
  • Replaces matching text.
  • Supports repeated searches through the same input.
Syntax:
Pattern pattern = Pattern.compile("regular_expression");
Matcher matcher = pattern.matcher("input");
boolean result = matcher.matches();Code language: JavaScript (javascript)
Example: Finding Numbers
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher("My number is 12345");

while (matcher.find()) {
    System.out.println(matcher.group());
}Code language: JavaScript (javascript)
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class MatcherDemo {
    public static void main(String[] args) {

        Pattern pattern = Pattern.compile("[0-9]+");

        String input = "Java 17 is released in 2021";

        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.println("Found: " + matcher.group());
        }
    }
}
Output:
Found: 17
Found: 2021

Methods of Matcher

Method Description Purpose
matches() Checks whether the entire input matches the pattern. Complete input validation.
find() Searches for the next matching sequence. Finds matches within text.
group() Returns the current matched text. Retrieves the match.
start() Returns the starting position of the current match. Finds where a match starts.
end() Returns the ending position of the current match. Finds where a match ends.
replaceAll() Replaces every matching sequence. Replaces all matches.
replaceFirst() Replaces the first matching sequence. Replaces the first match.
reset() Resets the matcher. Starts matching again from the beginning.
lookingAt() Checks whether the input starts with a matching pattern. Checks the beginning of text.
pattern() Returns the Pattern used by the matcher. Gets the associated pattern.
Scroll to Top