- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pattern pattern() method in Java with examples
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+)
Advertisements