如何在Java中使用正則表示式驗證給定的日期格式,例如MM-DD-YYYY?


Java的java.util.regex包提供了各種類來查詢字元序列中的特定模式。

此包的Pattern類是正則表示式的編譯表示。要將正則表示式與String匹配,此類提供兩種方法:

  • compile() − 此方法接受表示正則表示式的字串,並返回Pattern物件的例項。

  • matcher() − 此方法接受一個String值,並建立一個matcher物件,該物件將給定的String與當前Pattern物件表示的模式匹配。

以下是匹配dd-MM-yyyy格式日期的正則表示式:

^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$

因此,要驗證MM-DD-YYYY格式的日期字串:

  • 使用Pattern類的compile()方法編譯上述正則表示式,並檢索Pattern物件。

  • 使用上面獲得的物件,透過將所需的日期字串作為引數呼叫matcher()方法,並從此方法檢索Matcher物件。

  • Matcher類的matches()方法在匹配的情況下返回true,否則返回false。在從上一步獲得的matcher物件上呼叫此方法。

示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchingDate {
   public static void main(String[] args) {
      String date = "01/12/2019";
      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);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(date);
      boolean bool = matcher.matches();
      if(bool) {
         System.out.println("Date is valid");
      } else {
         System.out.println("Date is not valid");
      }
   }
}

輸出

Date is valid

更新於:2023年12月05日

4K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

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