Java 中的 Matcher pattern() 方法,附示例


java.util.regex.Matcher 類表示執行各種匹配操作的引擎。此類沒有建構函式,你可以使用類 java.util.regex.Pattern 的 matches() 方法建立/獲取此類的物件。

此類 (Matcher) 的 pattern() 方法獲取並返回當前 Matcher 解釋的 Pattern(物件)。

示例 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your date of birth (MM/DD/YYY)");
      String date = sc.next();
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(date);
      //Validating the date
      if(matcher.matches())
         System.out.println("Date is valid");
      else
         System.out.println("Date is not valid");
      //Retrieving Pattern used
      Pattern p = matcher.pattern();
      System.out.println("Pattern used to match the given date: \n"+p);
   }
}

輸出

Enter your date of birth
01/21/2019
Date is valid
Pattern used to match the given date:
^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$

示例 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternExample {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.next();
      //Regular expression to match word that starts with a digit
      String regex = "^[0-9].*$";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      Pattern p = matcher.pattern();
      System.out.println("Pattern used to match the given input string: "+p);
      //verifying whether match occurred
      if(matcher.matches())
         System.out.println("First character is a digit");
      else
         System.out.println("First character is not a digit");
   }
}

輸出

Enter a String
2sample
Pattern used to match the given input string: ^[0-9].*$
First character is a digit

更新於: 20-11-2019

281 次瀏覽

提升職業生涯

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.