Reputation: 11364
I have a folder which contains multiple Zip
files with different naming convention.
1.zip
Hello.zip
SomeNameWithAnyCharacter-Xal_Yal_Zal_12345-20180518-152147535.zip
I would like to get all zip files which has below naming convention:
[SomeNameWithAnyCharacter]-[Xal_Yal_Zal_][yyyyMMdd][HHmmssfff]
How to apply regex for below code in C#,
var allFiles = Directory
.GetFiles(@"C:\FilePath", "*.zip")
.Select(f => new FileInfo(f))
.OrderByDescending(fi => fi.LastWriteTimeUtc);
Upvotes: 1
Views: 338
Reputation: 186833
Add Where
with required regular expression:
var allFiles = Directory
.EnumerateFiles(@"C:\FilePath", "*.zip")
.Where(file => Regex.IsMatch(
Path.GetFileNameWithoutExtension(file), // match file name
@"Xal_Yal_Zal_[0-9]+-[0-9]{8}-[0-9]{9}$")) // with the required regex
.Select(file => new FileInfo(file))
.OrderByDescending(fi => fi.LastWriteTimeUtc);
Pattern: Xal_Yal_Zal_[0-9]+-[0-9]{8}-[0-9]{9}$
explained:
Xal_Yal_Zal_ - Xal_Yal_Zal_
[0-9]+ - one or more digits 0..9
- - minus sign
[0-9]{8} - 8 digits 0..9, e.g. 20180518
- - minus sign
[0-9]{9} - 9 digits 0..9, e.g. 152147535
$ - anchor - end of string
Upvotes: 4