Reputation: 2509
I'm creating a program in VB.NET to output multiple images. Some images will have the same file name. If there is multiple files with the same name I want to add "_1_" to the end of the file name. If the "_1_" file already exists I want to increment the 1 to be "_2_". If this file already exists I want to continue incrementing the number ultil it doesn't exist. So for example "filename", filename_1_", "filename_2_", etc. Here is the code that I have tried
Dim usedFiles As New List(Of String)
While usedFiles.Contains(returnValue)
If Regex.IsMatch(returnValue, "[_]([0-9]{1,})[_]$") Then
returnValue = Regex.Replace(returnValue, "[_]([0-9]{1,})[_]$", "_" + (CType("$1", Integer) + 1).ToString() + "_")
Else
returnValue += "_1_"
End If
End While
usedFiles.Add(returnValue)
The line that isn't working is:
returnValue = Regex.Replace(returnValue, "[_]([0-9]{1,})[_]$", "_" + (CType("$1", Integer) + 1).ToString() + "_")
which outputs "filename_2_" every time. I have also tried:
returnValue = Regex.Replace(returnValue, "[_]([0-9]{1,})[_]$", "_($1+1)_")
however this returns "filename_($1+1)_". I know I could just remove the "_" then add 1 to the number then put the "_" back on both sides, but I also know this can be done in other languages (like php) using the Regex.
Any ideas?
Thanks!
Ryan
Upvotes: 0
Views: 533
Reputation: 43743
I haven't taken the time to figure out what's wrong with your RegEx expression because it just seems silly to me. You're over thinking it. All you need to do is something simple like this:
Dim fileName As String = returnValue
Dim i As Integer = 0
While usedFiles.Contains(returnValue)
i = i + 1
returnValue = fileName + "_" + i.ToString() + "_"
End While
Upvotes: 1