Java中的正則表示式“d”結構


子表示式/元字元“\d”匹配數字。

示例 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "\d 24";
      String input = "This is sample text 12 24 56 89 24";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

輸出

Number of matches: 2

示例 2

以下是一個 Java 程式,該程式從使用者處讀取一個 10 位數。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main( String args[] ) {
      String regex = "\d{10}";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your phone number (10 digits): ");
      String input = sc.nextLine();
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher m = p.matcher(input);
      if(m.find()) {
         System.out.println("OK");
      } else {
         System.out.println("Wrong input");
      }
   }
}

輸出 1

Enter your phone number (10 digits):
9848022338
OK

輸出 2

Enter your phone number (10 digits):
545
Wrong input

更新於:19-11-2019

166 次檢視

開啟你的 職業道路

透過完成課程獲得證書

立即開始
廣告