是否使用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类的方法的以上表达式。
绕过所需的输入字符串作为matcher()Pattern类的方法的参数,获取Matcher对象。
matches()如果发生匹配,则Matcher类的方法返回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}$";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//匹配字符串中的已编译模式
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
matches()String类的方法接受正则表达式,并将当前字符串与之匹配,如果匹配则返回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();
//正则表达式以MM-DD-YYY格式接受日期
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