如何将文本从文本文件传输到按特定字符拆分的列表框?

How do I transfer text from a text file to a list box splitting on a certain character?

我有一个包含如下数据的文本文件:

[Section A]
55555
66666
77777 (all on separate lines)

[Section B]
AAAAA
BBBBB (each on a separate line)

我只是想知道如何读取这些数据,并将 [Section A] 中的数据仅放入 listboxA,将 [Section B] 中的数据放入 listboxB .

此代码取决于与您问题中描述的模式完全相同的模式。我将文本文件放在 bin\Debug 文件夹中进行测试,但如果位于其他位置,您将需要完整路径。

第一个 Do 循环查找 A 部分和 B 部分之间的空行。最后的 Do 循环在到达行数组末尾时停止。

Private Sub OpCode()
    Dim lines = File.ReadAllLines("Sections.txt")
    Dim index = 0
    If lines(0) = "[Section A]" Then
        index = 1
        Do While lines(Index) <> ""
            ListBox1.Items.Add(lines(index))
            index += 1
        Loop
    End If
    index += 1
    If lines(index) = "[Section B]" Then
        index += 1
        Do Until index = lines.Length
            ListBox2.Items.Add(lines(index))
            index += 1
        Loop
    End If
End Sub

Regex


通过Regex可以轻而易举。考虑以下示例:

Imports System.IO
Imports System.Text.RegularExpressions
'...

Private Sub TheCaller()
    Dim path = "TheFullPathOfTheTextFile"
    Dim patt = "(\[.*\]\s)([A-Za-z0-9\s\,.\-_!@#$%^&*()=+;:'`~|""?<>\/\]+)"
    Dim matches = Regex.Matches(File.ReadAllText(path),
                        patt, RegexOptions.Multiline).Cast(Of Match)

    If matches.Count = 2 Then
        ListBoxA.Items.AddRange(
            matches.First().Groups(2).Value.
            Split({ControlChars.NewLine}, StringSplitOptions.RemoveEmptyEntries)
            )
        ListBoxB.Items.AddRange(
            matches.Last().Groups(2).Value.
            Split({ControlChars.NewLine}, StringSplitOptions.RemoveEmptyEntries)
            )
    End If
End Sub

请注意,每个匹配项的 Groups(1) 捕获 [Section X] 部分,其中 X 在您的示例中为 ABGroups(2) 将部分的 data 捕获为字符串。在 vbCrLf 上拆分此字符串,即 ControlChars.NewLine 以获取字符串数组,以便您可以将它们插入到列表框中。

查看在线 Regex 测试 here


Extension Methods


或者,您可以通过 TakeWhile and SkipWhile 方法中继扩展以获取两个部分的数据:

Private Sub TheCaller()
    ListBoxA.DataSource = Nothing
    ListBoxB.DataSource = Nothing

    Dim allLines = File.ReadAllLines(path)

    ListBoxA.DataSource = allLines.Skip(1).
        TakeWhile(Function(x) x <> "[Section B]").
        Where(Function(x) Not String.IsNullOrWhiteSpace(x)).ToList

    ListBoxB.DataSource = allLines.SkipWhile(Function(x) x <> "[Section B]").
        Skip(1).Where(Function(x) Not String.IsNullOrWhiteSpace(x)).ToList
End Sub

注意:将列表框绑定到数据源作为手动添加项目的替代方法。

两个查询中的Skip方法都是跳过[Section x]行。


Loop


不使用任何扩展的简单 For..Each 循环:

Private Sub TheCaller()
    Dim listBox = ListBoxA

    For Each line In File.ReadAllLines(path)
        If line = "[Section B]" Then
            listBox = ListBoxB
            Continue For
        ElseIf line = "[Section A]" Then
            Continue For
        End If

        If Not String.IsNullOrWhiteSpace(line) Then
            listBox.Items.Add(line)
        End If
    Next
End Sub