English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
javajava.util.regexpackage provides various classes to find specific patterns in character sequences. The pattern class in this package is the compiled representation of regular expressions.
PatternThe classpattern()Methods obtain and return the regular expression as a string, and compile the current pattern using the regular expression.
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} //Create 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"); } //Retrieve the current pattern's regular expression String regularExpression = pattern.pattern(); System.out.println("Regular expression: ");+regularExpression); } }
Output result
Date is valid Regular expression: ^(1[0-2]|0[1-9])/(3[01])|[12])[0-9]|0[1-9])/[0-9]{4}
public class PatternExample { public static void main(String[] args) { String input = "Hi my id is 056E1563"; //Use group in regular expression String regex = ".(.*)?(\\d+)"; //Create 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"); } //Retrieve the current pattern's regular expression String regularExpression = pattern.pattern(); System.out.println("Regular expression: ");+regularExpression); } }
Output result
Match found Regular expression: (.*)?(\d+)