C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Between: This uses IndexOf and LastIndexOf to locate the positions of the two specified strings. It returns the substring in between.
IndexOfLastIndexOfBefore: This calls IndexOf to find the argument string. Then it returns the characters before that string's location.
After: This finds the last occurrence of the argument string with LastIndexOf. It then returns the substring before that point.
VB.NET program that uses Between, Before, After on Strings
Module Module1
Function Between(value As String, a As String,
b As String) As String
' Get positions for both string arguments.
Dim posA As Integer = value.IndexOf(a)
Dim posB As Integer = value.LastIndexOf(b)
If posA = -1 Then
Return ""
End If
If posB = -1 Then
Return ""
End If
Dim adjustedPosA As Integer = posA + a.Length
If adjustedPosA >= posB Then
Return ""
End If
' Get the substring between the two positions.
Return value.Substring(adjustedPosA, posB - adjustedPosA)
End Function
Function Before(value As String, a As String) As String
' Get index of argument and return substring up to that point.
Dim posA As Integer = value.IndexOf(a)
If posA = -1 Then
Return ""
End If
Return value.Substring(0, posA)
End Function
Function After(value As String, a As String) As String
' Get index of argument and return substring after its position.
Dim posA As Integer = value.LastIndexOf(a)
If posA = -1 Then
Return ""
End If
Dim adjustedPosA As Integer = posA + a.Length
If adjustedPosA >= value.Length Then
Return ""
End If
Return value.Substring(adjustedPosA)
End Function
Sub Main()
Dim test As String = "DEFINE:A=TWO"
' Test the Between Function.
Console.WriteLine(Between(test, "DEFINE:", "="))
Console.WriteLine(Between(test, ":", "="))
' Test the Before Function.
Console.WriteLine(Before(test, ":"))
Console.WriteLine(Before(test, "="))
' Test the After Function.
Console.WriteLine(After(test, ":"))
Console.WriteLine(After(test, "DEFINE:"))
Console.WriteLine(After(test, "="))
End Sub
End Module
Output
A
A
DEFINE
DEFINE:A
A=TWO
A=TWO
TWO
Tip: A Dictionary could be used to store the key and value pairs returned by the parsing method.
Dictionary