The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression.
Syntax:
public String pattern()
Parameters: This method does not accepts anything as parameter.
Return Value: This method returns the pattern’s source regular expression.
Below programs illustrate the pattern() method:
Program 1:
Java
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
String REGEX = "(.*)(for)(.*)?";
String actualString = "code of Machine";
Pattern pattern1 = Pattern.compile(REGEX);
String RegularExpression = pattern1.pattern();
System.out.println("Pattern's RegularExpression = "
+ RegularExpression);
}
}
|
Output:
Pattern's RegularExpression = (.*)(for)(.*)?
Program 2:
Java
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
String REGEX = "(.*)(ee)(.*)?";
String actualString = "geeks";
Pattern pattern1 = Pattern.compile(REGEX);
String RegularExpression = pattern1.pattern();
System.out.println("Pattern's RegularExpression = "
+ RegularExpression);
}
}
|
Output:
Pattern's RegularExpression = (.*)(ee)(.*)?
Program 3:
Java
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GFG {
public static void main(String[] args)
{
String input1
= "The quick brown fox jumps over the lazy dog";
String input2
= "The quick red fox jumps over the lazy dog";
String regex = "(?i)the";
Pattern pattern = Pattern.compile(regex);
Matcher matcher1 = pattern.matcher(input1);
Matcher matcher2 = pattern.matcher(input2);
while (matcher1.find()) {
System.out.println("Match 1: "
+ matcher1.group());
}
while (matcher2.find()) {
System.out.println("Match 2: "
+ matcher2.group());
}
}
}
|
Output
Match 1: The
Match 1: the
Match 2: The
Match 2: the
Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
24 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...