使用Java正则表达式接受日期字符串(MMddyyyy格式)吗?

使用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"); } } }登录后复制