VB.NET 在字符串中的两个单词之间查找文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24118188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET finding text between two words in a string
提问by Tharokiir
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.
所以我在为我在 Visual Basic 中开发的程序中添加的功能找到代码时遇到了麻烦。目前,它对文本文件进行排序,例如某些程序生成的日志,并显示该文件中包含给定字符串的所有行。我希望能够添加能够选择剪切显示行的某些部分并只显示我需要的信息的功能,例如:只打印字符串1之后,字符串2之前的行部分,或在两个字符串之间。任何帮助深表感谢。
回答by Jens
Use the .IndexOfand the Strings.Midfunctions to search your string and crop out the wanted part:
使用.IndexOf和Strings.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
This will search the string you input (sSource) for the occurances of the two words sDelimStartand sDelimEndand then use Strings.Midto crop out the parts in between the two words. You need to include the length of sDelimStart, because .IndexOfwill return the start of the word.
这将搜索你输入的字符串(sSource)两个词的occurancessDelimStart和sDelimEnd,然后用Strings.Mid在这两个词之间的裁剪出来的零件。您需要包括 的长度sDelimStart,因为.IndexOf将返回单词的开头。

