Extract dates from filename

Posted by Newbie on Stack Overflow See other posts from Stack Overflow or by Newbie
Published on 2010-06-15T03:22:23Z Indexed on 2010/06/15 4:02 UTC
Read the original article Hit count: 201

Filed under:
|

I have a situation where I need to extract dates from the file names whose general pattern is [filename_]YYYYMMDD[.fileExtension]

e.g. "xxx_20100326.xls" or x2v_20100326.csv

The below program does the work

//Number of charecter in the substring is set to 8 
//since the length of YYYYMMDD is 8

public static string ExtractDatesFromFileNames(string fileName)
{

    return fileName.Substring(fileName.IndexOf("_") + 1, 8);
}

Is there any better option of achieving the same?

I am basically looking for standard practice.

I am using C#3.0 and dotnet framework 3.5

Edit:

I have like the solution and the way of answerig of LC. I have used his program like

string regExPattern = "^(?:.*_)?([0-9]{4})([0-9]{2})([0-9]{2})(?:\\..*)?$";
string result =  Regex.Match(fileName, @regExPattern).Groups[1].Value;

The input to the function is : "x2v_20100326.csv"

But the output is: 2010 instead of 20100326(which is the expected one).

Can anyone please help.

© Stack Overflow or respective owner

Related posts about c#

Related posts about c#3.0