Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET finding text between two words in a string [closed]

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.

like image 547
Tharokiir Avatar asked Jun 09 '14 10:06

Tharokiir


1 Answers

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.

like image 152
Jens Avatar answered Sep 18 '22 23:09

Jens