pattern() method of thePattern 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 is used to get the same source expression.
Example 1: Using the pattern() methodto check the regex pattern passed for pattern matching.
// Java program to demonstrate// Pattern.pattern() methodimportjava.util.regex.*;publicclassGeeks{publicstaticvoidmain(String[]args){// create a REGEX StringStringREGEX="(.*)(for)(.*)?";// create the string in which you want// to searchStringactualString="code of Machine";// create patternPatternpattern1=Pattern.compile(REGEX);// find the regular expression of patternStringRegularExpression=pattern1.pattern();System.out.println("Pattern's RegularExpression = "+RegularExpression);}}
Pattern's RegularExpression = (.*)(for)(.*)?
public String pattern()
Example 2: Using the pattern() method inconjunction with aMatcher.
// Java program to demonstrate the usage of// regular expressions in pattern matchingimportjava.util.regex.Matcher;importjava.util.regex.Pattern;publicclassGeeks{publicstaticvoidmain(String[]args){// Input strings to match the regex againstStringinput1="The quick brown fox jumps over the lazy dog";Stringinput2="The quick red fox jumps over the lazy dog";// Regex pattern to match case-insensitive 'the'Stringregex="(?i)the";// Compile the regex patternPatternpattern=Pattern.compile(regex);// Create matchers for both input stringsMatchermatcher1=pattern.matcher(input1);Matchermatcher2=pattern.matcher(input2);// Find and print all matches in input1while(matcher1.find()){System.out.println("Match 1: "+matcher1.group());}// Find and print all matches in input2while(matcher2.find()){System.out.println("Match 2: "+matcher2.group());}}}
Match 1: TheMatch 1: theMatch 2: TheMatch 2: the
A
Introduction to Java
Java Programming Basics
Java Methods
Access Modifiers in Java
Arrays in Java
Java Strings
Regular Expressions in Java
Classes and Objects in Java
Java Constructors
Java OOP(Object Oriented Programming) Concepts
Java Packages
Java Interface
Collections in Java
Collections Class in Java
Collection Interface in Java
Iterator in Java
Java Comparator Interface
Java Exception Handling
Java Try Catch Block
Java final, finally and finalize
Chained Exceptions in Java
Null Pointer Exception in Java
Exception Handling with Method Overriding in Java
Java Multithreading Tutorial
Synchronization in Java
File Handling in Java
Java Method References
Java 8 Stream Tutorial
Java Networking
JDBC Tutorial
Java Memory Management
Garbage Collection in Java
Memory Leaks in Java
Java Interview Questions and Answers
Java Programs - Java Programming Examples
Java Exercises - Basic to Advanced Java Practice Programs with Solutions
Java Quiz
Java Project Ideas For Beginners and Advanced