VB.NET提取指定字符串间内容并循环添加至ListBox求助
修改建议:提取所有匹配字符串并添加至ListBox
原代码问题分析
你的extractStr函数仅能返回首个匹配结果,核心问题在于:
- 未循环遍历源字符串查找后续匹配项
- 未记录上次搜索的结束位置,无法从正确的位置开始下一次搜索
- 缺乏错误处理,当找不到起始/结束标记时会引发异常
重构后的提取函数
将函数改为返回所有匹配结果的集合,支持循环查找:
Public Function ExtractAllStrings(source As String, startMarker As String, endMarker As String) As List(Of String) Dim results As New List(Of String)() Dim currentPos As Integer = 1 ' 字符串索引从1开始,和VB6保持一致 Dim startLen As Integer = startMarker.Length Dim endLen As Integer = endMarker.Length Do ' 定位下一个起始标记 Dim startPos As Integer = InStr(currentPos, source, startMarker, CompareMethod.Text) If startPos = 0 Then Exit Do ' 无更多起始标记,退出循环 ' 从起始标记后定位结束标记 Dim endPos As Integer = InStr(startPos + startLen, source, endMarker, CompareMethod.Text) If endPos = 0 Then Exit Do ' 找不到对应结束标记,退出循环 ' 提取起始与结束标记之间的内容 Dim extractedLength As Integer = endPos - (startPos + startLen) + 1 Dim extractedText As String = source.Substring(startPos + startLen - 1, extractedLength) results.Add(extractedText) ' 更新搜索起始位置,避免重复匹配 currentPos = endPos + endLen Loop Return results End Function
修改后的按钮调用代码
在点击事件中获取所有匹配结果,添加至ListBox:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click ' 清空ListBox,避免重复内容 ListBox1.Items.Clear() ' 获取所有匹配项 Dim allMatches As List(Of String) = ExtractAllStrings(TxtScrape.Text, lblPreTickData1.Text, lblPreTickData2.Text) If allMatches.Count > 0 Then ' 显示第一个结果到文本框 TickerPRE.Text = allMatches(0) ' 将所有匹配项添加到ListBox For Each match As String In allMatches ListBox1.Items.Add(match) Next MsgBox($"找到 {allMatches.Count} 个匹配项") Else TickerPRE.Text = "" MsgBox("未找到匹配项") End If End Sub
关键改进点
- 使用
List(Of String)存储多结果,替代VB6的动态数组,更符合VB.NET的集合用法 - 循环遍历所有可能的匹配,通过
currentPos记录每次搜索的起始位置 - 添加了标记不存在时的退出逻辑,避免运行时异常
- 修正了字符串截取的长度计算,确保提取内容准确
内容的提问来源于stack exchange,提问作者dave fac
相关产品推荐
相关产品推荐

