java.regex软件包的模式类是正则表达式的编译表示。
此类的compile()方法接受表示正则表达式的字符串值并返回Pattern对象,以下是此方法的签名。
static Pattern compile(String regex)
此方法的另一个变体接受表示标志的整数值,以下是带有两个参数的compile方法的签名。
static Pattern compile(String regex, int flags)
该模式类提供各种领域每个代表一个标志
序号 | 栏位及说明 |
---|---|
1 | CANON_EQ 仅当两个字符规范相等时才匹配。 |
2 | CASE_INSENSITIVE 匹配字符,不区分大小写。 |
3 | 注释 允许空格和模式注释。 |
4 | DOTALL 启用dotall模式。哪里的“。” 元字符匹配所有字符,包括行终止符。 |
5 | LITERAL 启用模式的文字分析。也就是说,输入序列中的所有元字符和转义序列都被视为文字字符。 |
6 | MULTILINE 启用多行模式,即将整个输入序列视为单行。 |
7 | UNICODE_CASE 启用可识别Unicode的大小写折叠,即与CASE_INSENSITIVE一起使用时。如果使用正则表达式搜索Unicode字符,则两种情况的Unicode字符都将匹配。 |
8 | UNICODE_CHARACTER_CLASS 启用预定义字符类和POSIX字符类的Unicode版本。 |
9 | UNIX_LINES 该标志启用Unix行模式。 |
此类的flags()方法返回当前模式中使用的标志。
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(); //正则表达式以MM-DD-YYY格式接受日期 String regex = "^(1[0-2]|0[1-9])/ # For Month\n" + "(3[01]|[12][0-9]|0[1-9])/ # For Date\n" + "[0-9]{4}$ # For Year"; //创建一个Pattern对象 Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS); //创建一个Matcher对象 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()); } }
输出结果
Enter your name: Krishna Enter your Date of birth: 09/26/1989 Given date of birth is valid Flag used: 4