The java.util.regex package of java provides various classes to find particular patterns in character sequences. The pattern class of this package is a compiled representation of a regular expression.
The pattern() method of the Pattern class fetches and returns the regular expression in the string format, using which the current pattern was compiled.
Example 1
import java.util.regex.Pattern; public class PatternExample { public static void main(String[] args) { String date = "12/09/2019"; String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); if(pattern.matcher(date).matches()) { System.out.println("Date is valid"); } else { System.out.println("Date is not valid"); } //Retrieving the regular expression of the current pattern String regularExpression = pattern.pattern(); System.out.println("Regular expression: "+regularExpression); } }
Output
Date is valid Regular expression: ^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$
Example 2
public class PatternExample { public static void main(String[] args) { String input = "Hi my id is 056E1563"; //Regular expression using groups String regex = "(.*)?(\\d+)"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); if(pattern.matcher(input).matches()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } //Retrieving the regular expression of the current pattern String regularExpression = pattern.pattern(); System.out.println("Regular expression: "+regularExpression); } }
Output
Match found Regular expression: (.*)?(\d+)