Matcher 類 matches() 方法及 Java 示例


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

此類的 matches() 方法將字串與正則表示式所表示的模式(這二者在建立此物件時給出)進行匹配。如果匹配,此方法返回 true,否則返回 false。此方法的返回結果為 true,表示整個區域應該匹配。

示例

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchesExample {
   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 words that starts with digits
      String regex = "^[0-9].*$";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      //verifying whether match occurred
      boolean bool = matcher.matches();
      if(bool) {
         System.out.println("First character is a digit");
      } else{
         System.out.println("First character is not a digit");
      }
   }
}

輸出

Enter a String
4hiipla
First character is a digit

更新於: 19-11-2019

392 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始使用
廣告