so I'm having trouble finding the code for a feature I'm adding in a program I'm developing in Visual Basic. Currently it sorts through text files, for example logs generated by certain programs, and displays all lines in that file containing a string it's given. I'd like to be able to add the function of being able to choose to cut out certain parts of the displayed line and only show the information I need, for example: only print the part of the line after string1, before string 2, or between the two strings. Any help is much appreciated.
Use the .IndexOf
and the Strings.Mid
functions to search your string and crop out the wanted part:
Dim sSource As String = "Hi my name is Homer Simpson." 'String that is being searched
Dim sDelimStart As String = "my" 'First delimiting word
Dim sDelimEnd As String = "Simpson" 'Second delimiting word
Dim nIndexStart As Integer = sSource.IndexOf(sDelimStart) 'Find the first occurrence of f1
Dim nIndexEnd As Integer = sSource.IndexOf(sDelimEnd) 'Find the first occurrence of f2
If nIndexStart > -1 AndAlso nIndexEnd > -1 Then '-1 means the word was not found.
Dim res As String = Strings.Mid(sSource, nIndexStart + sDelimStart.Length + 1, nIndexEnd - nIndexStart - sDelimStart.Length) 'Crop the text between
MessageBox.Show(res) 'Display
Else
MessageBox.Show("One or both of the delimiting words were not found!")
End If
This will search the string you input (sSource
) for the occurances of the two words sDelimStart
and sDelimEnd
and then use Strings.Mid
to crop out the parts in between the two words. You need to include the length of sDelimStart
, because .IndexOf
will return the start of the word.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With