Java中的Pattern flags()方法及示例


java.regex 包中的 Pattern 類是正則表示式的編譯表示。

此類的 **compile()** 方法接受表示正則表示式的字串值,並返回一個 **Pattern** 物件,以下是此方法的簽名。

static Pattern compile(String regex)

此方法的另一個變體接受表示標誌的整數值,以下是帶有兩個引數的 compile 方法的簽名。

static Pattern compile(String regex, int flags)

**Pattern** 類提供各種欄位,每個欄位代表一個標誌。

序號欄位和描述
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("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

更新於:2019年11月20日

430 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.