latest tweets:

Jump to content.

Use C#’s regular expression library to Convert TimeSpan and DateTime to and from strings. (Named capturing groups!)

December 20th, 2010

Well that title is a mouthful.  Long story short, as an exercise in regular expressions I wrote a utility class to convert strings to TimeSpans and DateTimes in C#.  This made great usage of named capturing groups.  (The download to the source code is at the bottom of this post.)

Here is the DateTime regular expression.  Note that when I new the regular expression object, I set whitespace and casing ignoring.
image

Named capturing groups allows code like this:
image

In the end, the utility class allows code like this:
image

fun!  Download all of the code here.

Have any suggestions about the code?  Any neat C# features I should have used?  Comment below!

1 comment

  1. Paxswill posted on December 20, 2010:

    Not a C# feature, but I really like the Cocoa NSDate classes, specifically this constructor. It’s discouraged mainly because it’s English only, but if you limit yourself to that, it’s a really powerful method.

RSS feed for comments on this post.

Leave a comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Read more

« »