English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Thefrom java.util.regex.MatcherThis class represents an engine for performing various matching operations. This class has no constructor and can be usedmatches()
The method of the java.util.regex.Pattern class creates/Get the object of this class.
This class (Matcher) pattern()Method to get and return the Pattern (object) interpreted by the current Matcher.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your date of birth (MM/DD/YYY)) String date = sc.next(); 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); //Create a Matcher object Matcher matcher = pattern.matcher(date); //Date validation if(matcher.matches()) System.out.println("Date is valid"); else System.out.println("Date is not valid"); //Retrieval pattern used Pattern p = matcher.pattern(); System.out.println("Pattern used to match the given date: "+p); } }
Output Result
Enter your date of birth 01/21/2019 Date is valid Pattern used to match the given date: ^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9}4}
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternExample { public static void main(String args[]) { //Read a string from the user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.next(); //Regular expression to match words starting with a digit String regex = "^[0-9].*$"; //Compile the regular expression Pattern pattern = Pattern.compile(regex); //Retrieve the matcher object Matcher matcher = pattern.matcher(input); Pattern p = matcher.pattern(); System.out.println("Pattern used to match the given input string: ");+p); //Verify if a match occurs if(matcher.matches()) System.out.println("The first character is a digit"); else System.out.println("The first character is not a digit"); } }
Output Result
Enter a String 2sample Pattern used to match the given input string: ^[0-9].*$ The first character is a digit