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

后端 未结 4 598
名媛妹妹
名媛妹妹 2020-12-12 07:33
 Regex reg = new Regex(@\"^[0-9]*\\.wav\");
  Stack wavefiles= new Stack(Directory.GetFiles(\"c:\\\\WaveFiles\", \"*.wav\").Where(path =&         


        
相关标签:
4条回答
  • 2020-12-12 07:47

    You can also do it without Regex

    var files = Directory.GetFiles("c:\\WaveFiles", "*.wav")
                .Where(f => Path.GetFileNameWithoutExtension(f).All(char.IsDigit));
    
    0 讨论(0)
  • 2020-12-12 07:57

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

    0 讨论(0)
  • 2020-12-12 08:00

    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))));
    
    0 讨论(0)
  • 2020-12-12 08:11

    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);
    
    0 讨论(0)
提交回复
热议问题