我有一个如下所示的字符串:20/11/2019
我想检查是否:
- 第一个数字介于 1 到 31 之间
- 第二个数字介于 1 到 12 之间
- 第三个数字介于 2000 到 2999 之间
数字之间用“/”分隔。
<小时/>我尝试过使用正则表达式,但我不熟悉它。
if (ExpDate.matches("[1-31]/[1-12]/[2000-2999]")){
//something happens
}
有什么方法可以正确完成这个任务吗?
预先感谢您的帮助。
最佳答案
假设这不仅仅是使用正则表达式的练习,恕我直言,最好使用为此工作制作的工具。特别是因为人们可能会认为您会在应用程序中使用后面的日期。考虑使用 DateTimeFormatter
和 LocalDate
来管理相关对象。
DateTimeFormatter dfmtr =
DateTimeFormatter.ofPattern("dd/MM/uuuu").withResolverStyle(
ResolverStyle.STRICT);
for (String testDate : new String[] {
"20/11/1999", "31/11/2000", "20/11/2019", "32/33/2001",
"29/02/2016", "29/02/2015"
}) {
try {
LocalDate d = LocalDate.parse(testDate, dfmtr);
int year = d.getYear();
if (year < 2000 || year >= 3000) {
throw new DateTimeParseException(
"Year (" + year + ") out of specified range", "uuuu", 6);
}
System.out.println("VALID: " + testDate);
}
catch (DateTimeParseException dtpe) {
System.out.println("INVALID DATE: " + dtpe.getLocalizedMessage());
}
}
您甚至可以重新格式化错误消息以匹配默认消息,或使用您自己的消息代替默认消息。这还考虑了闰年和给定月份的正确日期。
关于java - 使用多个不同的数字范围检查字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58672895/