Minion Minion - 1 year ago 53 Question

Parsing string - "Contains" is insufficient

I use this code to check if a

is in another

If StringData(1).Contains("-SomeText2.") Then
'some code
End If

'StringData(1) looks like this:
'In case I look for -SomeText1. I need 1401
'In case I look for -SomeText2. I need 0802
'In case I look for -SomeText3. I need 23
'In case I look for -SomeText4. I need 104

I first check if
is in
, and if it is, I need to get the next part of the text:
which is the part I don't know how to do, how can I do it?

All the strings are separated by
and all substrings start and end with
and have a
separating the first part from the second. I check all the strings starting with
and ending with
because there are some with
in the middle, so
function won't work.

Those strings change quite often, so I need something to check it no matter the length of the strings.

Answer Source

I would just split the string up and get the text between "." and "-" when the search text is found like this:

    Dim str As String = "-SomeText1.1401-|-SomeText2.0802-|-SomeText3.23-|-SomeText4.104-"
    Dim searches() As String = {"-SomeText1", "-SomeText2", "-SomeText3", "-SomeText4"}
    For Each search As String In searches
        For Each value As String In str.Split(CChar("|"))
            If value.Contains(search) Then
                Dim partIwant As String = value.Substring(value.IndexOf(".") + 1, value.Length - value.IndexOf(".") - 2)
                'Outputs: 1401, 0802, 23, 104
                Exit For
            End If

In this example, we just use Contains() to see if our search string is present or not...we can't actually use that function to get any further information because all it returns is a True or False. So once we know that our string has been found, it's just a matter of some string manipulation to grab the text between the "." and "-" characters. IndexOf() will get us the index of the period, and then we just pull the text between there and the last character of the string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download