English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
java.regexThe pattern class in the software package is the compiled representation of a regular expression.
This classcompile()This method accepts a string value representing the regular expression and returnsPatternObject, here is the signature of this method.
static Pattern compile(String regex)
Another variant of this method accepts an integer value representing the flags, here is the signature of the compile method with two parameters.
static Pattern compile(String regex, int flags)
ThisPatternThe class provides various fields, each representing a flag
Number | Column and Description |
---|---|
1 | CANON_EQ Only when two character specifications are equalOnly whenMatches. |
2 | CASE_INSENSITIVE Matches characters without case sensitivity. |
3 | Comments Allows whitespace and pattern comments. |
4 | DOTALL Enables dotall mode. Where the dot (.) metacharacter matches any character, including line terminators. |
5 | LITERAL Enables pattern literal analysis. That is, all metacharacters and escape sequences in the input sequence are treated as literal characters. |
6 | MULTILINE Enables multiline mode, treating the entire input sequence as a single line. |
7 | UNICODE_CASE Enables the use ofRecognitionUnicode case folding, which is used with CASE_INSENSITIVE. If Unicode characters are searched using regular expressions, both cases of Unicode characters will match. |
8 | UNICODE_CHARACTER_CLASS Enables the predefined character classes and the Unicode version of POSIX character classes. |
9 | UNIX_LINES This flag enables Unix line mode. |
This classflags()The method returns the flags used in the current pattern.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class COMMENTES_Example { public static void main(String[] args) {}} Scanner sc = new Scanner(System.in); System.out.println("Enter your name:"); String name = sc.nextLine(); System.out.println("Enter your Date of birth:"); String dob = sc.nextLine(); //Regular expressions with MM-DD-YYY format accepts date String regex = "^(1[0-2]|0[1-9)]/ # For Month " + "(3[01]|[12]|0[-9]|0[1-9)]/ # For Date " + "[0-9]{4$# For Year"; //Create a Pattern object Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS); //Create a Matcher object Matcher matcher = pattern.matcher(dob); boolean result = matcher.matches(); if(result) { System.out.println("Given date of birth is valid"); } else { System.out.println("Given date of birth is not valid"); } System.out.println("Flag used: ");+ pattern.flags()); } }
Output Result
Enter your name: Krishna Enter your Date of birth: 09/26/1989 Given date of birth is valid Flag used: 4