我有一个包含如下音乐列表的文本文件:
BeginSong{
Song Name
Artist
Genre
}EndSong
这种情况有多种。
我想获取 and 之间的文本BeginSong{
并将}EndSong
歌曲信息放入字符串数组中。然后我想将每个实例添加到 ListBox 作为艺术家 - 歌曲名称(我确信我可以弄清楚这部分)。我希望这是一个清晰的描述。
我有一个包含如下音乐列表的文本文件:
BeginSong{
Song Name
Artist
Genre
}EndSong
这种情况有多种。
我想获取 and 之间的文本BeginSong{
并将}EndSong
歌曲信息放入字符串数组中。然后我想将每个实例添加到 ListBox 作为艺术家 - 歌曲名称(我确信我可以弄清楚这部分)。我希望这是一个清晰的描述。
使用ReadLine()
函数FileStream
由于您已经知道信息的顺序,您应该能够循环所有文件行并将它们存储在相应的属性中。
伪:
WHILE Reader.Read()
Store Line in BeginSongTextVariable
Read Next Line
Store Line in SongNameVariable
Read Next Line
Store Line in ArtistNameVariable
Read Next Line
Store Line in GenreVariable
Read Next Line
Store Line in EndSongTextVariable
Add The Above Variables in List
End While
Neolisk 有一个很好的答案,它使用正则表达式。但是由于除了 VB.NET 之外,您还包括了 VB6 标记,所以我将介绍一个 VB6 解决方案。
您可以使用字符串拆分功能,并在“结束”上拆分,即"BeginSong{"
和"}EndSong"
Dim songInfos As String
Dim firstArray() As String
Dim secondArray() As String
Dim thirdArray() As String
Dim songInfoArray() As String
Dim i As Integer
Dim songCounter As Integer
' to test:
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name1" & vbNewLine
songInfos = songInfos & "Artist1" & vbNewLine
songInfos = songInfos & "Genre1" & vbNewLine
songInfos = songInfos & "}EndSong" & vbNewLine
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name2" & vbNewLine
songInfos = songInfos & "Artist2" & vbNewLine
songInfos = songInfos & "Genre2" & vbNewLine
songInfos = songInfos & "}EndSong"
firstArray = Split(songInfos, "BeginSong{")
songCounter = 0
ReDim songInfoArray(2, 0)
For i = 1 To UBound(firstArray) Step 1
secondArray = Split(firstArray(i), "}EndSong")
thirdArray = Split(secondArray(0), vbNewLine)
songInfoArray(0, songCounter) = thirdArray(1)
songInfoArray(1, songCounter) = thirdArray(2)
songInfoArray(2, songCounter) = thirdArray(3)
songCounter = songCounter + 1
If i < UBound(firstArray) Then
ReDim Preserve songInfoArray(2, songCounter)
End If
Next i
最后一行之后的手表。ReDim
注意songInfoArray的结构,这是对其进行治疗所必需的
您可以对命名组使用正则表达式:
BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong
像这样的东西:
Imports System.Text.RegularExpressions
'...
Dim s As New Regex("BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong")
Dim mc As MatchCollection = s.Matches(inputFile)
For Each m As Match In mc
Dim song_name As String = m.Groups("song_name").Value
Dim artist As String = m.Groups("artist").Value
Dim genre As String = m.Groups("genre").Value
'use or store these values as planned
Next