Pattern Class in Java
Last Updated :
02 Mar, 2022
The two classes that support Regular Expression (Regex) are as follows, Pattern Class and Matcher Class. Both these classes work together. In simple language, we can think of them as, if we want to define a pattern( regular expression) then we use the Pattern Class and if we want to match that pattern against any other sequence, then we use the Matcher Class.
Pattern Class
As you can see in the image given below, 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.
Syntax:
static Pattern compile(String pattern)
Here, the pattern in the compile method is a String. This String (pattern ) is then converted into a pattern which can be now used for pattern matching by the Matcher Class. After the pattern is matched, it returns a Pattern object that contains the pattern. The Pattern object created here will now be used to create a Matcher. The Matcher is created by calling the matcher() method defined by Pattern.
Syntax:
Matcher matcher(CharSequence x)
Here, x is the character sequence against which the pattern will be matched. Since this is the input you are taking, it is also called the input sequence. CharSequence is an interface that provides read-only access to the set of characters.
Example 1:
Java
import java.util.regex.*;
class GFG {
public static void main(String[] args)
{
Pattern pattern = Pattern.compile( "GeeksforGeeks" );
Matcher matcher = pattern.matcher( "GeeksforGeeks" );
boolean letsCheck = matcher.matches();
System.out.println(
" Let us check whether the pattern matches or not:" );
if (letsCheck)
System.out.println( "Pattern Matched" );
else
System.out.println( "Pattern does not match" );
}
}
|
Output
Let us check whether the pattern matches or not:
Pattern Matched
Example 2:
Java
import java.util.regex.*;
class GFG {
public static void main(String[] args)
{
Pattern pattern = Pattern.compile( "GeeksforGeeks" );
Matcher matcher = pattern.matcher(
"GFG stands for GeeksforGeeks" );
System.out.println(
"Checking for GFG in GeeksforGeeks: " );
if (matcher.find())
System.out.println( "subsequence GFG found" );
else
System.out.println( "subsequence GFG not found" );
}
}
|
Output
Checking for GFG in GeeksforGeeks:
subsequence GFG found
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...