How to find files according RegEx in C#

前端 未结 3 473
名媛妹妹
名媛妹妹 2020-12-20 17:12

I need to get list of files on some drive with paths that matches specific pattern, for example FA\\d\\d\\d\\d.xml where \\d is digit (0,1,2..9). So files can have names lik

相关标签:
3条回答
  • 2020-12-20 17:32

    Use the Directory API to find FA????.xml, and run the resulting list through a regex filter:

    var fa = from f in Directory.GetFiles("FA????.xml")
             where Regex.Match(f, "FA\d\d\d\d\.xml")
             select f;
    
    0 讨论(0)
  • 2020-12-20 17:51

    You could do something like:

    System.IO.Directory.GetFiles(@"C:\", "FA????.xml", SearchOption.AllDirectories);
    

    Then from your results just iterate over them and verify them against your regex i.e. that the ? characters in the name are all numbers

    0 讨论(0)
  • 2020-12-20 17:53

    Are you using C# 3?

    Regex reg = new Regex(@"^FA[0-9]{4}\.xml$");
    var files = Directory.GetFiles(yourPath, "*.xml").Where(path => reg.IsMatch(path));
    
    0 讨论(0)
提交回复
热议问题