Java Matcher Class in the java.util.regex Package

The java.util.regex.Matcher class is mainly used to interpret the pattern of an input string and determine whether it matches a given pattern.

Matcher Methods

Method Description
matches() Returns true if the pattern matches the entire string.
boolean find() Returns true if the pattern matches, and moves to that position. If there are multiple matches, it can be called repeatedly.
boolean find(int start) Searches for a match starting after the start position.
String group() Returns the matched part.
String group(int group) Returns the matched part for the specified group number.
int groupCount() Returns the total number of groups in the pattern, specified with parentheses.
int start() Returns the start position of the matched string.
int start(int group) Returns the start position of the matched specified group.
int end() Returns the position after the end of the matched string.
int end(int group) Returns the position after the end of the matched specified group.

Matcher Example

The following code displays only words made up of lowercase letters. For example, words that include uppercase letters or special characters, such as I and it., are excluded.

package com.devkuma.basic.matcher;

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

public class MatcherTutorial {
    
    public static void main(String[] args) {
        String regEx = "[a-z]*[a-z]";
        String text = "I never dreamed about success, I worked for it.";

        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

The result is as follows.

never
dreamed
about
success
worked
for
it