问题
I have a string representing a date, for example "2010.12.25"
. How can I control if it is of "yyyy.MM.dd" format? There is no need to check the validness of the date.
回答1:
You have the Regex, in Groovy, you can just do:
boolean match = "2010.12.12" ==~ /\d{4}\.\d{2}\.\d{2}/
回答2:
use SimpleDateFormat
to parse()
the string, handling the exception to decide if it is a valid date string. don't use regex to check a date. e.g.:
2010.30.40
2010.13.34
回答3:
try {
Date.parse('yyyy.MM.dd', '2013.12.21')
} catch(java.text.ParseException p) {
println "Unparseable Date"
}
You can also use Groovy Date parsing to check the accuracy of date format.
回答4:
You can check the format of the date by using a SimpleDateFormat like this, because using regex
for validating date formats is a very bad practice, IMHO.
String strDate = "2010.12.25";
DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
try {
Date date = df.parse(strDate);
// If it comes here, then its a valid format
} catch (ParseException pe) {
// If it comes here, then its not a valid date of this format.
}
回答5:
Try to this check this with method isValid(String dateStr)
,
boolean isValid(String dateStr) {
Matcher matcher=
Pattern.compile("\\d{4}\\.\\d{2}\\.\\d{2}").matcher(dateStr);
return matcher.matches();
}
回答6:
Try this one
String a = "2010.12.12";
System.out.println(a.matches("\\d{4}\\.\\d{2}\\.\\d{2}"));
Output will be true
来源:https://stackoverflow.com/questions/20143208/groovy-java-regex-check-if-yyyy-mm-dd-format