Java 中的 Pattern flags() 方法示例

javaobject oriented programmingprogramming更新于 2024/5/7 4:28:17

java.regex 包的 pattern 类是正则表达式的编译表示。

此类的 compile() 方法接受表示正则表达式的字符串值并返回 Pattern 对象,以下是此方法的签名。

static Pattern compile(String regex)

此方法的另一种变体接受表示标志的整数值,以下是带有两个参数的 compile 方法的签名。

static Pattern compile(String regex, int flags)

Pattern 类提供各种字段,每个字段代表一个标志

S.No字段和说明
1CANON_EQ
仅当两个字符在规范上相等时才匹配它们。
2CASE_INSENSITIVE
匹配字符而不考虑大小写。
3COMMENTS
允许模式中存在空格和注释。
4DOTALL
启用 dotall 模式。其中“.”元字符匹配包括行终止符在内的所有字符。
5LITERAL
启用模式的文字解析。即,输入序列中的所有元字符和转义序列都被视为文字字符。
6MULTILINE
启用多行模式,即,整个输入序列被视为一行。
7UNICODE_CASE
启用 Unicode 感知大小写折叠,即与 CASE_INSENSITIVE 一起使用时。如果您使用正则表达式搜索 Unicode 字符,则两种情况的 Unicode 字符都会被匹配。
8UNICODE_CHARACTER_CLASS
启用预定义字符类和 POSIX 字符类的 Unicode 版本。
9UNIX_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("输入您的姓名:");
      String name = sc.nextLine();
      System.out.println("输入您的出生日期:");
      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])/ # 表示日期\n"
+ "[0-9]{4}$ # 表示年份";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
      //创建一个 Matcher 对象
      Matcher matcher = pattern.matcher(dob);
      boolean result = matcher.matches();
      if(result) {
         System.out.println("给定的出生日期有效");
      } else {
         System.out.println("给定的出生日期无效");
      }
      System.out.println("使用的标记:"+ pattern.flags());
   }
}

输出

输入您的姓名:
Krishna
输入您的出生日期:
09/26/1998
给定的出生日期有效
使用的标记:4

相关文章


有用资源