2

我有一个包含很多文件的文件夹,它们是根据其中带有迭代编号的模式命名的。

我正在尝试通过vb.net. 目的是用文件夹的最高编号+1命名它

在那里,我在互联网上查找了很多关于正则表达式和 Linq 的东西,这帮助我编写了以下代码:

If tmpFileName.Contains("%num%") Then
        Dim lastFileNo As Integer = 1
        Dim tmpFName = Dir(frmMain.saveLocalTFPath & "*.docx")
        Dim numbers() As Integer = Regex.Split(tmpFName, "(?<alpha>[\w-[0-9]]+)(?<num>[\d]+)").Skip(1).Select(Function(s) Integer.Parse(s)).ToArray
        For Each element In numbers
            If element > 0 And element < 999 And element > lastFileNo Then lastFileNo = element
        Next
        Do Until tmpFName = ""
            numbers = Regex.Split(tmpFName, "(?<alpha>[\w-[0-9]]+)(?<num>[\d]+)").Skip(1).Select(Function(s) Integer.Parse(s)).ToArray
            For Each element In numbers
                If element > 0 And element < 1000 And element > lastFileNo Then lastFileNo = element
            Next
            tmpFName = Dir()
        Loop
        tmpFileName = tmpFileName.Replace("%num%", lastFileNo)
    End If

但它没有按预期工作。这是我在 Linq 和 Regex 中的第一个代码,我不习惯检测我的代码中的问题。有人可以给个提示吗?

谢谢

4

3 回答 3

1

我很确定你的正则表达式是错误的。稍微拆分您的代码,创建一个从文件名中提取数字的函数。前任

Function GetNumberFromFilename(ByVal filename As String) As Integer

    ' From the filename parameter, pull the number and return it
End Function

然后就很容易测试了

Console.WriteLine(GetNumberFromFilename("JCR 2013-01 data.docx"))

当你开始工作时,只需循环所有文件即可获得最高数字

Dim lastFileNo As Integer = 1
Dim files() As String = IO.Directory.GetFiles(frmMain.saveLocalTFPath, "*.docx")

For Each file As String In files
    Dim number As Integer

    number = GetNumberFromFilename(file)

    If number > 0 And number < 1000 And number > lastFileNo Then
        lastFileNo = number
    End If
Next
于 2013-07-19T13:19:36.523 回答
1

这将是一些可能的解决方案之一。

 Dim di As New System.IO.DirectoryInfo("The Directory")
 Dim max = (From f In di.GetFiles().AsQueryable()
           Where IsNumeric(Path.GetFileNameWithoutExtension(f.Name))
           Select Path.GetFileNameWithoutExtension(f.FullName)).
           OrderBy(Function(c) c).LastOrDefault()
于 2013-07-19T13:59:08.200 回答
0

是的 the_lotus 你是对的,但matches在我的情况下,而不是match. 我在 30 分钟前发现了它,但我想在发布解决方案之前让它工作。

多亏了你,我设法组装了和平,这是正确的代码:

Dim lastFileNo As Integer = 1
Dim files() As String = Directory.GetFiles(frmMain.saveLocalTFPath, "*.docx")

For Each file As String In files
    file = Path.GetFileNameWithoutExtension(file)
    Dim numbers As MatchCollection = Regex.Matches(file, "(?<num>[\d]+)")

    For Each number In numbers
        number = CInt(number.ToString())
        If number > 0 And number < 1000 And number > lastFileNo Then lastFileNo = number
    Next
Next
于 2013-07-19T17:14:59.633 回答