![]() |
VOOZH | about |
The Pattern class in Java is used for defining regular expressions (regex) to perform pattern matching on strings. It is part of the java.util.regex package and it plays a key role in searching, replacing, and manipulating strings based on patterns. The Matcher class works together with Pattern to perform regex operations like finding matches in text.
Example: Basic Pattern Matching
Pattern Matched
Explanation: In the above example, the Pattern.compile("GeeksforGeeks") method compiles the string "GeeksforGeeks" into a pattern. The m.matches() checks if the entire input string exactly matches the pattern.
As we can see in the below image, the Pattern Class belongs to java.util.regex (package), and the package belongs to java.base (module). The pattern class defines no constructor.
So, let us see how a pattern is created. The pattern is created using the compile() factory method.
Pattern Class1. compile(String pattern): Compiles the given regex into a Pattern object, which can be used for matching operations.
static Pattern compile(String pattern)
2. matcher(CharSequence input): Creates a Matcher object for a given input string. The Matcher is used to perform matching operations like matches(), find(), and replaceAll().
Matcher matcher(CharSequence input)
Example: Searching for Substrings with the find() Method
The find() method of the Matcher class is used to search for the next subsequence that matches the pattern in the input string. The find() method can locate the pattern within a larger string.
Subsequence GFG found
Explanation: In the above example, the Pattern.compile("GeeksforGeeks") method creates a pattern to search for "GeeksforGeeks". The matcher.find() searches for the occurrence of the pattern in the input string and returns true if found, otherwise false.