Converting SimpleDateFormat date format to Regular Expression
Is there a generic way to convert the SimpleDateFormat date format to a regular expression开发者_JAVA技巧 in Java?
For simple expressions you can just do
String dateFormat = "yyyy/MM/dd HH:mm:ss.SSS";
String regexFormat = dateFormat.replaceAll("[mHsSdMy]", "\\d");
However to produce something which validates is far more complex. e.g. when MM=03, dd must be between 01 and 31, however when MM=02, dd must between 01 and 28 or 29 (depending on the year)
If you use MMM, DDD, ZZZ its much more complex and locale dependant.
No, nothing ready-to-use. And regex does not have knowledge about date constraints - for example what GMT is, or what am/pm is. For simplest cases you can use \d{2}-\{2}-\d{4}
(dd-MM-yyyy
), otherwise stick to SimpleDateFormat
(or joda-time DateTimeFormat
)
精彩评论