Reputation: 2014
I have a stack overflow question regarding the following code:
For Each DeltaCharB As Char In DeltaString
If DeltaCharB = "[" Then
Dim DeltaIndexB As Integer = TB8.IndexOf("[B|")
Dim DeltaStringB As String = TB8.Substring(DeltaIndexB + 3, TB8.IndexOf("]", DeltaIndexB + 1) - DeltaIndexB - 3)
MsgBox(DeltaStringB)
Else
'Do nothing
End If
Next
The issue created is that if the code is run X number of times that the character "[" is found, The string is displayed the same X amount of times in a messagebox.
However I only want to have it processed 1X. I have tried to change the following line but as i expected only one character at a time is permitted.
If DeltaCharB = "[B|" Then
Typically the string used to search in would be as follows:
{[A|Text belonging to entry A][B|Text belonging to entry B][C|Text belonging to entry C]}.... ect...ect
Dose anybody know how to resolve this?
Upvotes: 0
Views: 1505
Reputation: 82474
Why do you need a loop? Your delimiters are well defined, you can just do this:
Function GetContent(byval input as string, byval delimiter as string) as string
Dim fullDelimiter = "["& delimiter &"|"
Dim BeginPosition as Integer = input.IndexOf(fullDelimiter)
if BeginPosition > -1 then
BeginPosition += fullDelimiter.Length
Dim EndPosition = input.IndexOf("][", BeginPosition)
if EndPosition > -1 then
return input.SubString(BeginPosition, EndPosition - BeginPosition)
end if
end if
return ""
End Function
And the usage:
Dim s as string = "[A|Text belonging to entry A][B|Text belonging to entry B][C|Text belonging to entry C]"
Dim content = GetContent(s, "B")
content now contains "Text belonging to entry B"
Note that with this code, the delimiter can by a string of any length between [
and |
.
A more general solution that will fit any input format would mean to also accept the end delimiter in the function:
Function GetContent(byval input as string, byval FromDelimiter as string, byval ToDelimiter as string) as string
Dim BeginPosition as Integer = input.IndexOf(FromDelimiter)
if BeginPosition > -1 then
BeginPosition += FromDelimiter.Length
Dim EndPosition = input.IndexOf(ToDelimiter, BeginPosition)
if EndPosition > -1 then
return input.SubString(BeginPosition, EndPosition - BeginPosition)
end if
end if
return ""
End Function
Upvotes: 3