Chinna Eranna wrote:I dont think SimpleDateFormat will here. Because SimpleDateFormat will parse this string successfully (after removing spaces), and gives a date of March 2nd or 3rd.
SimpleDateFormat extends java.text.DateFormat which has a method setLenient( boolean) which by default is 'true'. Set to 'false' and then it will throw the exception.
I'm a great fan of regex but this is not the right place to use it. Especially since the OP's regex allows '-' as a field separator but the SimpleDateFormat
pattern does not! I would not even use a regex to convet the '-' separators to '/'; I would just use String.replace() .
My suggestion is to split the string and validate using a simple algorithm. Having a complex regex will make code unreadable.
If one has to check the syntax before parsing then I would use a regex and I would comment the regex so that it is not unreadable.