VB.NET Get String Betwen Two Strings - Not Working With Escaped Chars
I am trying to find a string inbetween two other strings. This function is working fine but as soon as I use escaped characters ("") it stops working and a runtime error occurs. Function & working / non-working examples below:
Function:
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
Example working:
Dim Haystack As String = "hello find me world"
Dim FindIt As String = GetBetween(Haystack, "hello", "world")
MessageBox.Show(FindIt)
Example non-working (Using escaped """ Chars):
Dim Haystack A开发者_JS百科s String = "<input type=""hidden"" name=""testsubmit"" id=""testsubmit"" value=""findme"" />"
Dim FindIt As String = GetBetween(Haystack, "id=""testsubmit"" value=""", """")
MessageBox.Show(FindIt)
Error: ArgumentOutOfRangeException was unhandled Length cannot be less than zero. Parameter name: length
So basically my function is not allowing me to use it when searching for escaped chars.
You can easily determine that the problem has nothing to do with escaped quotes by replacing them in your string with some other character and seeing that the function call fails in exactly the same way.
The real difference between your two test strings is that in your first example, your needle_two
string does not appear in your needle
string, while in your second example it does. In other words, your problem is that you start looking for needle_two
where needle
begins rather than where it ends, and istop
ends up inside of needle
.
What you need to do is start searching after needle
stops:
Dim istop As Integer = InStr(istart + Len(needle), haystack, needle_two)
精彩评论