首頁  >  文章  >  Java  >  使用Java正規表示式接受日期字串(MM-dd-yyyy格式)嗎?

使用Java正規表示式接受日期字串(MM-dd-yyyy格式)嗎?

WBOY
WBOY轉載
2023-09-07 18:05:021333瀏覽

使用Java正規表示式接受日期字串(MM-dd-yyyy格式)嗎?

以下是符合 dd-MM-yyyy 格式日期的正規表示式。

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

符合該格式字串中的日期。

  • 編譯上面的compile()方法的表達式Pattern 類別。

  • 繞過所需的輸入字串作為 Pattern 類別的 matcher() 方法的參數來取得 Matcher 物件。

  • 如果符合發生,Matcher 類別的 matches() 方法傳回 true,否則傳回 false。因此,請呼叫此方法來驗證資料。

範例1

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

String 類別的matches() 方法接受正規表示式並將目前字串與之匹配,如果匹配則傳回true,否則傳回false。因此,要驗證給定日期(字串格式)是否符合所需格式 -

  • #取得日期字串。
  • 呼叫 matches( ) 方法,將上述正規表示式作為參數傳遞給它。

範例2

import java.util.Scanner;
public class Just {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.nextLine();
      System.out.println("Enter your Date of birth: ");
      String dob = sc.nextLine();
      //Regular expression to accept date in MM-DD-YYY format
      String regex = "^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$";
      boolean result = dob.matches(regex);
      if(result) {
         System.out.println("Given date of birth is valid");
      } else {
         System.out.println("Given date of birth is not valid");
      }
   }
}

輸出1

Enter your name:
Janaki
Enter your Date of birth:
26/09/1989
Given date of birth is not valid

輸出2

Enter your name:
Janaki
Enter your Date of birth:
09/26/1989
Given date of birth is valid

以上是使用Java正規表示式接受日期字串(MM-dd-yyyy格式)嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除