我只是想知道是否有一种方法(也许使用正则表达式)来验证Java桌面应用程序上的输入是否是格式为“ YYYY-MM-DD”的字符串。
我搜索了但没有成功。
谢谢
我只是想知道是否有一种方法(也许使用正则表达式)来验证Java桌面应用程序上的输入是否是格式为“ YYYY-MM-DD”的字符串。
我搜索了但没有成功。
谢谢
使用以下正则表达式:
^\d{4}-\d{2}-\d{2}$
如
if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
...
}
使用该matches方法时,锚点^和$(分别是字符串的开始和结尾)隐式存在。
您需要的不止一个regex,例如“ 9999-99-00”不是有效日期。有一个SimpleDateFormat内置的类可以做到这一点。重量更重,但功能更全面。
例如
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
boolean isValidDate(string input) {
try {
format.parse(input);
return true;
}
catch(ParseException e){
return false;
}
}
不幸的是,SimpleDateFormat它既笨重又不是线程安全的。
放在一起:
REGEX 不验证值(例如“ 2010-19-19”)
SimpleDateFormat 不检查格式(接受“ 2010-1-2”,“ 1-0002-003”)
必须同时验证格式和值:
public static boolean isValid(String text) {
if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
return false;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
try {
df.parse(text);
return true;
} catch (ParseException ex) {
return false;
}
}
ThreadLocal可用于避免为每个调用创建新的SimpleDateFormat。
由于SimpleDateFormat不是线程安全的,因此在多线程上下文中是必需的:
private static final ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
System.out.println("created");
return df;
}
};
public static boolean isValid(String text) {
if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
return false;
try {
format.get().parse(text);
return true;
} catch (ParseException ex) {
return false;
}
}
(可以对Matcher进行相同的操作,这也不是线程安全的)
举报