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 次浏览

开启您的 职业生涯

完成课程获得认证

开始使用
广告