How to order list of files by file name with number?

后端 未结 2 562
春和景丽
春和景丽 2020-11-28 17:14

I have a bunch of files in a directory that I am trying to get based off their type. Once I have them I would like to order them by file name (there is a number in them and

2条回答
  •  伪装坚强ぢ
    2020-11-28 17:14

    I'm assuming the file and .txt parts are mutable, and just here as placeholders for file names and types that can vary.

    I don't use regular expressions very often, so this may need some work yet, but it's definitely the direction you need to go:

    Dim exp As String = "-([0-9]+)[.][^.]*$"
    documentPages = Directory.GetFiles(documentPath, "*.txt").OrderBy(Function(p) Integer.Parse(Regex.Matches(p, exp)(0).Groups(1).Value)).ToList()
    

    Looking again, I see I missed that you are filtering by *.txt files, which can help us narrow the expression:

    Dim exp As String = "-([0-9]+)[.]txt$"
    

    Another possible improvement brought by the other answer that includes test data is to allow for whitespace between the - and numerals:

    Dim exp As String = "-[ ]*([0-9]+)[.]txt$"
    

    It's further worth noting that the above will fail if there are text files that don't follow the pattern. We can account for that if needed:

    Dim exp As String = "-[ ]*([0-9]+)[.][^.]*$"
    Dim docs = Directory.GetFiles(documentPath, "*.txt")
    documentPages = docs.OrderBy(
         Function(p) 
                Dim matches As MatchCollection = Regex.Matches(p, exp)
                If matches.Count = 0 OrElse matches(0).Groups.Count < 2 Then Return 0
                Return Integer.Parse(matches(0).Groups(1).Value)
         End Function).ToList()
    

    You could also use Integer.MaxValue as your default option, depending on whether you want those to appear at the beginning or end of the list.

提交回复
热议问题