Java Intermediate

0% completed

Previous
Next
Matcher Class in Java

The Matcher class is part of Java’s regular expression package (java.util.regex). It works with a compiled regular expression (a Pattern object) to perform match operations on a character sequence (such as a string). The Matcher class provides methods to check if the pattern matches the input, to search for occurrences, and to extract or manipulate matched subsequences. This lesson will introduce the key methods of the Matcher class and demonstrate how to use them with simple examples.

Key Methods of the Matcher Class

The table below summarizes some of the essential methods provided by the Matcher class:

MethodReturn TypeDescription
matches()booleanAttempts to match the entire region against the pattern.
find()booleanSearches for the next subsequence of the input that matches the pattern.
group()StringReturns the input subsequence matched by the previous match operation.
start()intReturns the start index of the previous match.
end()intReturns the offset after the last character matched.
replaceAll(String replacement)StringReplaces every subsequence of the input sequence that matches the pattern with the given replacement string.

Examples

Example 1: Using matches() and find()

In this example, we demonstrate the difference between matches() and find(). The code uses a regex to search for a pattern in a given string.

Java
Java

. . . .

Example Explanation:

  • The regex pattern "cat" is compiled and matched against the input string.
  • matches() returns false because the entire string does not exactly match "cat".
  • find() returns true because the substring "cat" is found in the input.
  • The methods group(), start(), and end() provide details about the match.

Example 2: Removing Matches with replaceAll()

This example shows how to use the replaceAll() method of the Matcher class to replace all occurrences of a pattern in a string with a specified replacement.

Java
Java

. . . .

Example Explanation:

  • The regex pattern \d{3}-\d{3}-\d{4} is compiled to match phone numbers in the format "123-456-7890".
  • The replaceAll("[PHONE]") method replaces every occurrence of the pattern with the string "[PHONE]".
  • The output shows the input string with phone numbers replaced by the placeholder.

Understanding the Matcher class enables you to leverage the full power of regular expressions in Java for tasks such as text validation, searching, and modification.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next