c# - Extract dates from filename -


I have a situation where I need to remove the date from the filename whose normal pattern is [filename_] YYYYMMDD [.fileExtension]

Example "xxx_20100326.xls" or x2v_20100326.csv

The following program works Pigment 8 is set in the number pigment / YYYYMMDD length 8 public static string ExtractDatesFromFileNames (string filename) {return fileName.Substring (fileName.IndexOf ("_") + 1, 8); }

Is there a better option to get the same?

I am basically looking for standard practice.

I am using C # 3.0 and edit the .NET Framework 3.5

:

I have the solution and the answer to the LC. I used my program like

  string regExPattern = "^ (?:. * _)? ([0- 9] {4}) ([0- 9] {2}) Is (? [0-9] {2}) (: \\ .. *) $ "; String result = Regex.Match (filename, @regExPattern). group 1]. value; The input in the  

function is: "x2v_20100326.csv"

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

I Regex, especially if the file name has more than one underscore then you can capture the year, month, day, and if necessary, a date time < / Code> You can make sure that the file name is correct Remove Ag and it really matches the pattern to be searched for.

For the pattern [filename_] YYYYMMDD [.fileExtension] , I'm thinking something like this:

^ (?:. * _ )? ([0- 9] {4}) ([0- 9] {2}) ([0- 9] {2}) (?: \ .. *)? $

Then your occupation group will be year, month and day in that order.

Explanation:

^ : The beginning of your string.

(?:. * _)? : An optional non-capturing group, which contains characters characterized by any underscore.

([0-9] {4}) : A capturing group containing a four digit figure.

([0-9] {2}) : A capturing group containing two digit figures.

(?: \ .. *)? : An optional non-capturing group, which includes a dot after any number.

$ : The end of your string.

However, I will add it if you make sure that there is only one underscore in your files, and underline that date, you have a code cleaner and possibly a bit out of regex Will be faster. It is something to keep in mind based on expected input set.


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -