In the first few weeks after posting my date regex, (http://www.regexlib.com/REDetails.aspx?regexp_id=113) which validated mm-dd-yyyy format I received several request for a dd-mm-yyyy version. I reluctantly fulfilled these request. After the 3rd request I was about to post it the regexlib site only to see it had been done for me (http://www.regexlib.com/REDetails.aspx?regexp_id=151)
(Thanks Marco). Now when I add a new version of the date regex I’m usually proactive. I’ll do a m-d-, d-m-y and a y-m-d. There were two reasons I was reluctant to do the d-m-y format. One: because of the use of a backreference and not know how to exclude groups at the time, my constantly miscounting parenthesis made it harder to get working properly. And secondly I already had a solution to the problem that didn’t require writing another complex regex but a simple one.
My original intent was to use the regex in web page validation so it was included in a javascript function isUSDate() which was something (but not exactly) like this
IsUSDate(strDate){
var re = new RegExp("the actual date regexp would go here");
return re.test(strDate) /* Return true if there is a match
}
Which would basically return true if the input (strDate) was a valid date in the mm/dd/yyyy format in the given range (year 1600+), false otherwise.
My solution to for other formats was to reformat the input and use the isUSDate function
Just about all the examples I’d seen for the replace method showed how to reverse two words
(\+w)(\s+)(\w+)
re.replace(“Hello World”,”$3$2$1”)
would return the string “World Hello”
In the replace function $1 is your first backreference (Hello). $2 the second (the space) and $3 your third backreference (World) and your specify their new order.
I just did that with the date.
For the sake if this example let’s assume all years are 4 digit years.
First use another but simple regex (\d\d?)(\D)(\d\d?)(\D)(\d{4})
Which validates the date format dd-mm-yyyy (or mm-dd-yyyy) but not the range of days and months but I would use it to capture the days and month values. Then swap the month and days with the regex replace method.
IsEuroDate(strDate){
Var strNewDate
Var re = new Regexp(“(\d\d?)(\D)(\d\d?)(\D)(\d{4})”)
strNewDate = re.replace(strDate,”$3$2$1$4$5”) \* swap month and day *|
Return IsUSDate(strNewDate)
}
Doing yyyy-m-d format is just as easy
IsISODate(strDate){
Var strNewDate
Var re = new Regexp(“(\d{4}) (\D)(\d\d?)(\D)(\d\d?)”)
strNewDate = re.replace(strDate,”$3$2$5$4$1”) \* move year to the end *|
Return IsUSDate(strNewDate)
}
If you are use the date regex inside a piece of code, not only is this method simple
But you could add another function that call the other functions allow you to accept multiple input formats. Although it wouldn’t be useful to accept m-d-y and d-m-y unless you also had someway of know which was used since 1-2-2004 would be valid in both formats but one is Jan 2nd and the other is Feb 1st.