使用Java正則表示式接受日期字串(MM-dd-yyyy格式)?
以下是匹配 dd-MM-yyyy 格式日期的正則表示式。
^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$在字串中匹配該格式的日期。
使用 Pattern 類的 compile() 方法編譯上述表示式。
透過將所需的輸入字串作為引數傳遞給 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
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP