JAVA 正则验证dd-MMM-yyyy
时间: 2023-07-04 07:04:28 浏览: 120
你可以使用以下正则表达式来验证dd-MMM-yyyy格式的日期:
```
^(0?[1-9]|[12][0-9]|3[01])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$
```
这个正则表达式可以匹配形如01-Jan-2022的日期格式,其中:
- ^ 和 $ 表示匹配整个字符串
- (0?[1-9]|[12][0-9]|3[01]) 表示匹配1到31的天数,0?表示0或1个0,[1-9]表示1到9,[12][0-9]表示10到29,3[01]表示30或31
- (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) 表示匹配英文月份的缩写
- \d{4} 表示匹配4位数字的年份
你可以使用Java的Pattern类和Matcher类来进行正则表达式匹配,示例代码如下:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateValidator {
private static final String DATE_PATTERN = "^(0?[1-9]|[12][0-9]|3[01])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{4}$";
private static final Pattern pattern = Pattern.compile(DATE_PATTERN);
public static boolean validate(String date) {
Matcher matcher = pattern.matcher(date);
return matcher.matches();
}
public static void main(String[] args) {
String date = "01-Jan-2022";
if (validate(date)) {
System.out.println("日期格式正确!");
} else {
System.out.println("日期格式不正确!");
}
}
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/plain; charset=us-ascii](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)