简体   繁体   中英

How to use Regex to filter file names in c#?

 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?

You can also do it without Regex

var files = Directory.GetFiles("c:\\WaveFiles", "*.wav")
            .Where(f => Path.GetFileNameWithoutExtension(f).All(char.IsDigit));

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))));

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);

Regex reg = new Regex(@"^[0-9] .wav"); wavefiles = new Stack(Directory.GetFiles(FolderName, " .wav").Where(path => reg.IsMatch(Path.GetFileName(path))));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM