How to grab a string that is between 2 strings

2019-08-05 14:33发布

问题:

I was used to VB6 using the split method as the following:

Split(Split(strLOL,strCool)(1),strCOOL)(0)

With this i was able to grab a string that was between 2 strings for example.

"en_us":"hi",

strLOL was for example: "en_US":" and strCool was ",

So it would grab the string between those two.

How am i possible to do this within VB.NET?

Edit: Let me set this straight. "en_us":"hi", is a string i have in a text file... I have a textbox that contains "en_us":"hi", and i want to grab everything between

  • "en_us":" and
  • ",

So the desired result is: hi

回答1:

Let me set this straight. "en_us":"hi", is a string i have in a text file... I have a textbox that containts: "en_us":"hi", and i want to grab everything between "en_us":" and ", So the response would be: hi

You would use String.Substring in .NET if you want to return a string between two other substrings. You use String.IndexOf to find the index of the substrings:

Dim str = IO.File.ReadAllText(pathToTextFile) '  "en_us":"hi",
Dim grabBetween1 = """en_us"":"""
Dim grabBetween2 = ""","
Dim indexOf = str.IndexOf(grabBetween1)

Dim result As String
If indexOf >= 0 Then ' default is -1 and indices start with 0
    indexOf += grabBetween1.Length ' now we look behind the first substring that we've already found
    Dim endIndex = str.IndexOf(grabBetween2, indexOf)
    If endIndex >= 0 Then
        result = str.Substring(indexOf, endIndex - indexOf)
    Else
        result = str.Substring(indexOf)
    End If
End If

Result is: hi

If you insist on using String.Split or you want to see what is the equivalent in .NET, here it is:

Dim result = str.Split({grabBetween1}, StringSplitOptions.None)(1).Split({grabBetween2}, StringSplitOptions.None)(0)

which also returns hi. However, that is less readable, much more error-prone, and less efficient.



回答2:

You will get the proper result if you use:

Dim str = """en_us"":""hi"","   ' This outputs a string with the value `"en_us":"hi",`
Console.WriteLine(str.Split("""")(2)) ' This will get you the string `hi`


标签: vb.net vb6 split