I would use a regex, especially if it had more than one underscore. Then you can capture the year, month, day and, if necessary, return a DateTime . This way you can make sure that you are extracting the desired part of the file name, and this really matches the pattern you are looking for.
For the template [filename_]YYYYMMDD[.fileExtension] I think something like:
^(?:.*_)?([0-9]{4})([0-9]{2})([0-9]{2})(?:\..*)?$
Then your captured groups will be year, month and day in that order.
Explanation:
^ : start of line.
(?:.*_)? : An optional non-capture group containing any number of characters followed by an underscore.
([0-9]{4}) : A capture group containing exactly four digits.
([0-9]{2}) : A capture group containing exactly two digits.
(?:\..*)? : An optional non-capture group containing a dot followed by any number of characters.
$ : end of your line.
However, I will add that if you are sure that your file names have one and only one underscore, and the date follows the underscore, the code you have is cleaner and will probably be slightly faster than the regular expression. This must be kept in mind based on the expected set of input data.
source share