

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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+)
- Related Questions & Answers
- Pattern compile() method in Java with Examples
- Pattern matcher() method in Java with examples
- Pattern quote() method in Java with examples
- Pattern matches() method in Java with examples
- Pattern split() method in Java with examples
- Pattern splitAsStream() method in Java with examples
- Pattern toString() method in Java with examples
- Pattern flags() method in Java with examples
- Pattern asPredicate() method in Java with examples
- Matcher pattern() method in Java with Examples
- Pattern CANON_EQ field in Java with examples
- Pattern CASE_INSENSITIVE field in Java with examples
- Pattern COMMENTS field in Java with examples
- Pattern DOTALL field in Java with examples
- Pattern LITERAL field in Java with examples
Advertisements