java正则日期校验yyyy-MM-dd HH:mm:ss
时间: 2023-07-19 11:18:27 浏览: 187
可以使用Java中的正则表达式来校验日期格式为yyyy-MM-dd HH:mm:ss的字符串,示例代码如下:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateValidator {
private static final String DATE_REGEX = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$";
private static final Pattern DATE_PATTERN = Pattern.compile(DATE_REGEX);
public static boolean validate(String dateStr) {
Matcher matcher = DATE_PATTERN.matcher(dateStr);
return matcher.matches();
}
}
```
其中,DATE_REGEX是用来校验日期格式的正则表达式,^表示字符串的开始,\d表示数字字符,{4}表示重复4次,-表示连字符,$表示字符串的结尾。
DATE_PATTERN是用来编译正则表达式的Pattern对象,validate方法则是用来执行校验的,它将传入的日期字符串与正则表达式进行匹配,如果匹配成功,则返回true,否则返回false。
相关问题
java 正则精准校验日期 yyyy-MM-dd HH:mm:ss
可以使用以下正则表达式进行精准校验日期 yyyy-MM-dd HH:mm:ss:
```java
String regex = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$";
```
然后使用 `Pattern` 类和 `Matcher` 类进行校验,示例代码如下:
```java
String input = "2021-12-31 23:59:59";
String regex = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.out.println("日期格式正确");
} else {
System.out.println("日期格式不正确");
}
```
输出结果为:日期格式正确。
时间格式校验yyyy-MM-dd HH:mm:ss
可以使用正则表达式来校验时间格式:
```python
import re
def check_time_format(time_str):
pattern = re.compile(r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$')
match = pattern.match(time_str)
if match:
return True
else:
return False
```
这个函数接收一个字符串类型的时间,如果符合 yyyy-MM-dd HH:mm:ss 的格式,返回 True,否则返回 False。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)