Daily Static

Technology, Dynamic Programming and Entrepreneurship

This page is powered by Blogger. Isn't yours?
Wednesday, February 26, 2003
 
Dotnet Regular Expressions

There is a really nice feature included with the dotnet Regular Expression engine that allows
named group captures. While it doesn't change the way the engine works, it adds a nice touch
to the capture process.

Say you had a string with the following format:

NWCRTN3497497349834_022502_93212.txt

This is an actual file I receive on a daily basis. Every day the file needs to be processed and
I need to mark some records in the database, refelecting that their change in status relates
to the date of this file. NWCRTN is always present, followed by a series of numbers for identification
purposes. Following these numbers is an underscore (_) followed by a six digit date and another
underscore. Following the date are some more numbers and the file extension.

All I need from this string is the date, and I need to reformat it to MM/YY/DD. I pulled the date out
using the following Regex pattern: @"(_(?<month>\d{2})(?<day>\d{2})(?<year>\d{2})_)"

this code snipped pulls the date out and reformats it:


private string GetDateFromFileName(string fileName)
{
     string pattern = @"(_(?<month>\d{2})(?<day>\d{2})(?<year>\d{2})_)";
     Regex reg = new Regex(pattern);

     Match m = reg.Match(fileName);

     return m.Groups["month"].Value + "\\" + m.Groups["day"].Value + "\\" + m.Groups["year"].Value;

}

Wallah, I have the reformatted date without using any fixed position string parsing.


Comments: Post a Comment