Thursday, January 22, 2015

Regular Expression for Timestamp value

Given string: 2012-02-10 00:00:00
Task: Check if it matches java.sql.Timestamp format.
Solution: use the regular expression
((1\d{3})|(20\d{2}))-((0[1-9])|(1[0-2]))-((0[1-9])|([1-2]\d)|(3[0-1])) (([0-1]\d)|(2[0-3])):([0-5]\d):([0-5]\d)|(^$)

Java way:
String pattern = "(((1\\d{3})|(20\\d{2}))-((0[1-9])|(1[0-2]))-((0[1-9])|([1-2]\\d)|(3[0-1])) (([0-1]\\d)|(2[0-3])):([0-5]\\d):([0-5]\\d))|(^$)";

NOTE: the regular expression above allows empty values as well, remove |(^$) from the end of the expression to get rid of it.

PS: if you'd like to know more about regular expressions and play with it go to