正则表达式日历验证 [英] Regex calendar validation
问题描述
我正在尝试创建一个用户输入日期(任何日期)的程序,例如 29-Jul-1995 。该程序应与日期格式匹配,并验证此日期是否正确。
I am trying to make a program where the user enters a date(any date), for example 29-Jul-1995. The program should match the date format and validate if this date is correct or not.
这是我的代码:
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Review1_Main {
public static Pattern pattern;
public static Matcher matcher;
// DATE_PATTERN is a format for user input
private static final Pattern DATE_PATTERN = Pattern.compile("(0?[1-9]|[12][0-9]|3[01])-(^[a-zA-Z]+$)-((19|20)\\d\\d)");
// Date format validation
public static boolean dateValidation(String date) {
matcher = pattern.matcher(date);
if(matcher.matches()) {
matcher.reset();
if (matcher.find()) {
int day = 01;
String month = "Jan";
int year = 2000;
if(day == 31 && !month.equals("Apr") || !month.equals("Jun") ||
!month.equals("Sep") || !month.equals("Nov")) {
return false;
} else if(month.equals("Feb")) {
// LEAP year validation
if (year % 4 == 0) {
if (day == 30 || day == 31) {
return false;
} else {
return true;
}
} else {
if (day == 29 || day == 30 || day == 31) {
return false;
} else {
return true;
}
}// end of year % 4
} else {
return true;
}// end of day.equals
} else {
return false;
} // end of matcher.find
} else {
return false;
}// end of matcher.matcher
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String dateInput = "29-Jul-1995";
dateValidation(dateInput);
}
} // end of class
但是某些原因,当我尝试编译它时,我总是得到这个错误:
But for some reason, when I try to compile it, I always get this error:
Exception in thread "main" java.lang.NullPointerException
at Review1_Main.dateValidation(Review1_Main.java:22)
at Review1_Main.main(Review1_Main.java:73)
第22行是:
matcher = pattern.matcher(date);
和73行是:
dateValidation(dateInput);
我对我的语法道歉。
谢谢。
推荐答案
你在构造函数中初始化 pattern
但是使用了它以静态方法 dateValidation
。除非在调用方法之前使用 new
构造了一个对象,否则静态字段将不会被初始化(因此空指针异常)。
You are initialising pattern
in the constructor but using it in a static method dateValidation
. Unless you have constructed an object using new
before calling the method then the static field will not be initialised (hence the null pointer exception).
解决方法是将模式转换为常量而不是在构造函数中编译它:
The solution is to turn your pattern into a constant rather than compiling it in the constructor:
private static final Pattern DATE_PATTERN = Pattern.compile("...");
然后使用常量(而不是模式
)创建匹配器
:
And then use the constant (rather than pattern
) to create the Matcher
:
Matcher matcher = DATE_PATTERN.match(dateInput);
您不需要模式
或 matcher
静态变量。
请注意,您没有理由使用静态方法。更好的方法是将其称为 DateValidator
类,并使验证方法成为实例方法。模式仍然可以是常数。
Note that there's really no reason for you to be using a static method. Better would be to call this a DateValidator
class and make the validation method an instance method. The pattern can still be a constant.
这篇关于正则表达式日历验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!