How to get string between two certain strings in Swift?

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 As 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.

  • Answer:

    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)

Chris at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.