我有一个包含如下数据的文本文件:
[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
循环到达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
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
是A
或B
。 Groups(2)
将段的data
捕获为字符串。在vbCrLf
(即ControlChars.NewLine
)上分割此字符串以获取字符串数组,以便可以将其插入到ListBoxes中。
请参见在线正则表达式测试here。>>
扩展方法
将列表框绑定到数据源,作为手动添加项目的替代方法。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