VB.net: Get a String between 2 words(any text) inside a larger string – Supereasy!

First off, I didn’t not write this code. I might have modified it but I’m not sure since I’ve had it around for quite some time.
If you’re the creator, thanks! It’s been handy. And comment and I’ll add a “credit-link” in this post. 😉

The code to get the value, text or string or whatever you choose to call it is so easy to use, short and it’s handy in many different kind of applications.
If you’re writing a Scraper in VB.net, this is a perfect Function that surely will be useful for you.

Lets say you have a string with the following content:
"Erik Johan Jonas Johanna Martin David"

And you want to pick out the name between Johanna and David:

Dim FindIt As String = GetBetween(Haystack, "Johanna", "David")

So, I used Dim in the same line to set up a string to store the text we’re picking out and then used the function called GetBetween to extract the text.
There will be spaces that you might want to use Trim on since I didn’t include the space as a prefix and suffix when using the GetBetween function.

The code is in the full post. Follow the link!

Add this Function inside a module

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 + Len(needle), haystack, needle_two)
If istop > 0 Then
Dim value As String = haystack.Substring(istart + Len(needle) - 1, istop - istart - Len(needle))
Return value
Catch ex As Exception
Return ""
End Try
End If
End If
Return ""
End Function

This code goes in a button or whatever you prefer to use:

Dim Haystack As String = "Erik Johan Johanna Martin David"
Dim FindIt As String = GetBetween(Haystack, "Johanna", "David")

And that will show a Msgbox with the text ” Martin “.

Simple and really useful, eh?