我如何将文本从文本文件传输到以特定字符分割的列表框? [关闭]

问题描述 投票:0回答:2

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

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

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

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

vb.net winforms file text listbox
2个回答
0
投票

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

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

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

0
投票

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]部分,在您的示例中,XABGroups(2)将段的data捕获为字符串。在vbCrLf(即ControlChars.NewLine)上分割此字符串以获取字符串数组,以便可以将其插入到ListBoxes中。

请参见在线正则表达式测试here。>>


扩展方法


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

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]行。


循环


一个简单的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
© www.soinside.com 2019 - 2024. All rights reserved.