I have a folder with a lot of files, they're named based on a pattern with an iterating number in it.
I'm trying to save new files through vb.net
. The aim is to name it with the highest number of the folder +1
There for I looked on internet and found a lot of things about regex and Linq which helped me to make the following code :
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
But it doesn't work as expected. Has it is my first code in Linq and in Regex and i'm not used to detect what is wrong in my code. Can someone give a hint please?
Thanks
Yes the_lotus you're right but with matches
in my cases instead of match
.
I discovered it 30 minutes ago but I wanted to make it work before posting the solution.
Thanks to you I managed to assemble the peaces and this is the right code:
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