Java中的Pattern flags()方法及示例
java.regex 包中的 Pattern 类是正则表达式的编译表示。
此类的 **compile()** 方法接受表示正则表达式的字符串值,并返回一个 **Pattern** 对象,以下是此方法的签名。
static Pattern compile(String regex)
此方法的另一个变体接受表示标志的整数值,以下是带有两个参数的 compile 方法的签名。
static Pattern compile(String regex, int flags)
**Pattern** 类提供各种字段,每个字段代表一个标志。
| 序号 | 字段和描述 |
|---|---|
| 1 | CANON_EQ 仅当两个字符在规范上相等时才匹配。 |
| 2 | CASE_INSENSITIVE 不区分大小写地匹配字符。 |
| 3 | COMMENTS 允许在模式中使用空格和注释。 |
| 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();
//Regular expression to accept date in MM-DD-YYY format
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";
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
//Creating 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());
}
}输出
Enter your name: Krishna Enter your Date of birth: 09/26/1989 Given date of birth is valid Flag used: 4
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP