我有一个包含大量文件的文件夹,它们是根据带有迭代编号的模式命名的。
我正在尝试通过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中的第一个代码,我不习惯检测代码中的错误。 有人可以提示吗?
由于
答案 0 :(得分: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
答案 1 :(得分: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()
答案 2 :(得分: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