Reputation: 1
Regex reg = new Regex(@"^[0-9]*\.wav");
Stack<string> wavefiles= new Stack<string>(Directory.GetFiles("c:\\WaveFiles", "*.wav").Where(path => reg.IsMatch(path)));
what I am trying to do in the above code is to get all the wave files with names having only digits. for example "123.wav"
when I try the above code it does not return any files ?
any ideas what is wrong with my code?
Upvotes: 0
Views: 2826
Reputation: 1
Regex reg = new Regex(@"^[0-9].wav"); wavefiles = new Stack(Directory.GetFiles(FolderName, ".wav").Where(path => reg.IsMatch(Path.GetFileName(path))));
Upvotes: 0
Reputation: 15354
You can also do it without Regex
var files = Directory.GetFiles("c:\\WaveFiles", "*.wav")
.Where(f => Path.GetFileNameWithoutExtension(f).All(char.IsDigit));
Upvotes: 3
Reputation: 8037
Directory.GetFiles
gives you a list of file names including the paths. You are trying to match your regex on results like this:
"C:\WaveFiles\123.wav".
You are expecting this entire string to start with a digit, and then contain only digits up to the ".wav" part, which of course won't match any of your files.
You might also want to replace [0-9]
by \d
for digits but that's a matter of preference.
Try this:
Regex reg = new Regex(@"^\d+\.wav");
string[] waveFilePaths = Directory.GetFiles("C:\\WaveFiles", "*.wav");
Stack<string> filesWithOnlyDigits = new Stack<string>(waveFilePaths
.Where(path => reg.IsMatch(Path.GetFileName(path))));
Upvotes: 1
Reputation: 7586
Your regex string is a little off, but not bad. I'd really do
Regex(@"^\d+\.wav$");
Which will match all file names that have one or more digits as their name and wav as their extension.
The real issue here is that all of your strings start with C:\WaveFiles\
which is why your regex is failing.
You will want to add a line to get the filename from the full path:
Path.GetFilename(path);
Upvotes: 0