VB.NET在字符串中的两个单词之间查找文本

Tha*_*iir 4 vb.net sorting string

所以我很难找到我在Visual Basic中开发的程序中添加的功能的代码.目前,它通过文本文件进行排序,例如某些程序生成的日志,并显示该文件中包含给定字符串的所有行.我希望能够添加能够选择剪切显示行的某些部分并仅显示我需要的信息的功能,例如:只打印string1之前的字符串部分,字符串2之前,或两个字符串之间.任何帮助深表感谢.

Jen*_*ens 9

使用.IndexOfStrings.Mid函数搜索字符串并裁剪出想要的部分:

    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
Run Code Online (Sandbox Code Playgroud)

这将搜索你输入的字符串(sSource)两个词的occurances sDelimStartsDelimEnd,然后用Strings.Mid在这两个词之间的裁剪出来的零件.你需要包括长度sDelimStart,因为.IndexOf将返回单词的开头.