0% completed
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.
The table below summarizes some of the essential methods provided by the Matcher
class:
Method | Return Type | Description |
---|---|---|
matches() | boolean | Attempts to match the entire region against the pattern. |
find() | boolean | Searches for the next subsequence of the input that matches the pattern. |
group() | String | Returns the input subsequence matched by the previous match operation. |
start() | int | Returns the start index of the previous match. |
end() | int | Returns the offset after the last character matched. |
replaceAll(String replacement) | String | Replaces every subsequence of the input sequence that matches the pattern with the given replacement string. |
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.
Example Explanation:
"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.group()
, start()
, and end()
provide details about the match.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.
Example Explanation:
\d{3}-\d{3}-\d{4}
is compiled to match phone numbers in the format "123-456-7890".replaceAll("[PHONE]")
method replaces every occurrence of the pattern with the string "[PHONE]".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.
.....
.....
.....