Tuesday, 8 September 2009

Regular expression for changing DateTime.Parse(mm/dd/yyyy) into new DateTime(yyyy, mm, dd)

In my previous post I bemoaned my lack of Regex skills and the fact that the VS2010 Training Kit startdates were fixed to use DateTime.Parse() rather than new DateTime(). I always use new DateTime() because it removes the mm/dd versus dd/mm problem. I've revisited the problem, in part to try and improve my Regex skills, and here is my solution.

Pattern:

DateTime\.Parse\("(\d{1,2})/(\d{1,2})/(\d{4})"\)

Replace:

new DateTime($3, $1, $2)

Good news / bad news time. That will work programmatically using the .NET Framework's Regex.Replace() method, BUT NOT in find / replace. Curses! The curlies get read as a "tag" by the find/replace tool, by which they mean capture group. Also, "\d" doesn't appear to be recognised and needs to be replaced with ":d". So that means I need to ask it to find one or two digits, then one or two digits, then four digits. I can use a hat "^" to specify a count. Finally, rather than using the "$" to place a capture group in the replace, it wants a "\". So that leaves my pattern looking like this:

DateTime\.Parse\("{(:d|:d^2)}/{(:d|:d^2)}/{:d^4}"\)

and leaves my replace looking like this:

new DateTime(\3, \1, \2)

Phew! I'm going for a lie down...

No comments: