Este código reemplaza una palabra en un string, por una secuencia numérica:
#Region " Replace Word (Increment method) "
' [ Replace Word (Increment method) ]
'
' // By Elektro H@cker
'
' Examples :
' MsgBox(Replace_Word_By_Increment("Hello World!, Hello World!", "Hello", , 3)) ' Result: 001 World!, 002 World!
Private Function Replace_Word_By_Increment(ByVal str As String, _
ByVal replace As String, _
Optional ByVal IgnoreCase As System.StringComparison = StringComparison.CurrentCulture, _
Optional ByVal DigitLength As Long = 0) As String
Dim str_split() As String = str.Split
Dim replacement As String = Nothing
Dim IndexCount As Long = 0
DigitLength = If(DigitLength = 0, replace.Length, DigitLength)
For Item As Long = 0 To str_split.LongCount - 1
If str_split(Item).Equals(replace, IgnoreCase) Then
replacement &= Threading.Interlocked.Increment(IndexCount).ToString
While Not replacement.Length >= DigitLength
replacement = replacement.Insert(0, "0")
End While
str_split(Item) = replacement
replacement = Nothing
End If
Next Item
Return String.Join(Convert.ToChar(Keys.Space), str_split)
End Function
#End Region
Este código reemplaza un patrón de búsqueda en un string, por una secuencia numérica:
#Region " Replace String (Increment method) "
' [ Replace String (Increment method) ]
'
' // By Elektro H@cker
'
' Examples :
' MsgBox(Replace_String_By_Increment("Hello World!, Hello World!", New System.Text.RegularExpressions.Regex("Hello\sWorld", RegexOptions.IgnoreCase), 3)) ' Result: 001!, 002!
Private Function Replace_String_By_Increment(ByVal str As String, _
ByVal replace As System.Text.RegularExpressions.Regex, _
Optional ByVal DigitLength As Long = 0) As String
DigitLength = If(DigitLength = 0, replace.ToString.Length, DigitLength)
Dim IndexCount As Integer = 0
Dim replacement As String = Nothing
Dim matches As System.Text.RegularExpressions.MatchCollection = replace.Matches(str)
For Each match As System.Text.RegularExpressions.Match In matches
replacement &= Threading.Interlocked.Increment(IndexCount).ToString
While Not replacement.Length >= DigitLength
replacement = replacement.Insert(0, "0")
End While
str = replace.Replace(str, replacement, 1, match.Index - (match.Length * (IndexCount - 1)))
replacement = Nothing
Next
matches = Nothing
replacement = Nothing
IndexCount = 0
Return str
End Function
#End Region
EDITO:Un sencillo proyecto para testear:
Descarga: http://www.mediafire.com/?6b6qdy9iyigm63v