Regular expressions in VS

Today one of the new developers on our team made a textbook mistake when creating test data for one of our system. He crafted by hand dozens of objects that would initialize repositories used by the system and wrote a bunch of tests that asserted overall flow and transformations of that data.

This worked really well, and we decided to use this data for initial UAT tests. But after deployment a straightforward error kept appearing:

String was not recognized as a valid DateTime.

First glance at the code and a sudden realization

new CashFlow {
    CreatedDate = DateTime.Parse("12/01/2018"),
    LastUpdateDate = DateTime.Parse("20/01/2018"),
    Value = 10600

This will work great if date format remains DD-MM-YYYY. But some systems (thank you USA) use different date formats. This code won’t work there.

A quick search for DateTime.Parse show, that there are dozens of different entries there and each seemed to have a unique date inside. So much for replacing strings idea.

I shuddered inside, but I knew the answer… regular expressions…

Using well-known regex online editor I quickly came up with the regex that correctly captures offending strings with an additional advantage of assigning groups to day, month and year values:


Now I know there is a way to reuse those groups, but I can never remember what character I have to use in Visual Studio to access them.

It’s $

So since DateTime constructor accepts arguments starting with a year I needed to reverse the order when feeding them back:


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

And with one swift ‘Replace all’ all was well again (even after deployment to UAT).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s