GetBetween()
Public Function GetBetween(ByVal haystack As String, ByVal needle As String, ByVal needle_two As String) As String
Dim istart As Integer = InStr(haystack, needle)
If istart > 0 Then
Dim istop As Integer = InStr(istart, haystack, needle_two)
If istop > 0 Then
Dim value As String = haystack.Substring(istart + Len(needle) - 1, istop - istart - Len(needle))
Return value
End If
End If
Return Nothing
End Function
GetAllBetween()
This code will allow you to not only get a string between two other strings from within a string, it can return all substrings that you are searching for inbetween at once. For example, this would be a good way to pull all of the names from an HTML file that fall between <span> and </span>.
Public Function GetAllBetween(ByVal Haystack As String, ByVal Needle As String, ByVal Needle2 As String) As List(Of String)
'Declare a list of strings to return
Dim StringList As List(Of String) = New List(Of String)
'We will set the haystack to 0 when no more objects are found
While Haystack <> ""
'Checks to see if an object is found
If GetBetween(Haystack, Needle, Needle2) Is Nothing Then
'Since no more strings were found - we set the haystack to blank to end the loop
Haystack = ""
'If an string was found
Else
'Check to see if the found item already exists
If StringList.Contains(GetBetween(Haystack, Needle, Needle2)) Then
'Remove the part of the haystack before where the already found part is
Haystack = Haystack.Substring(Haystack.LastIndexOf(GetBetween(Haystack, Needle, Needle2)))
'If the string hasn't already been found
Else
'Add the new found object to the list
StringList.Add(GetBetween(Haystack, Needle, Needle2))
End If
End If
End While
'Send the list of strings back
Return StringList
End Function
No comments:
Post a Comment