What is a regex.Matcher class in Java?

A regular expression​ is a defined pattern used for matching and manipulating strings. In Java, there is a built-in API for regular expressions:

java.util.regex package

This package has three classes:

  1. Pattern class
  2. Matcher class
  3. PatternSyntaxException class

This regular expression is not the property of one particular programming language; instead, it is supported by multiple languages.

svg viewer

Matcher class

The util.regex.Matcher is used for match operations using the text patterns. Some of the most commonly used methods are:

Methods Description
find() It searches the occurrences of an expression in a text.
find(int index) It searches the occurrences of an expression in a text from the given index.
start() It returns the starting index of the match that is found.
end() It returns the ending index of the match that is found.
groupCount() It returns an integer value for the total number of matched values.

Code

// Java program
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main
{
public static void main(String [] arguments)
{
// Create a pattern to be searched
Pattern pttrn = Pattern.compile("Ah*");
// Search the pattern in the given text
Matcher mtch = pttrn.matcher("Ahhhhh! I lost my job.");
// search and print the starting and ending index using
// end() and start() function.
while (mtch.find())
System.out.println("Starting index: " + mtch.start() +
" Ending index: " + (mtch.end()-1));
}
}

In the above code, some of the functions from the pattern class are used. These are detailed here.

The “*” symbol in the above code means that the character before it can repeat finitely at that position (e.g., hel*o is equivalent to hello).

Copyright ©2024 Educative, Inc. All rights reserved