VB.NET 文本文件解析多个条目,一行由 Space 分隔

VB.NET Text File Parse Many Entries One Line Separated by a Space

感谢您提供的任何指导。

我想读取一个文本文件并使用 space 作为分隔符捕获所有值,然后将每个条目输入到我的 SQL 服务器 table 上的一个字段中。有时条目是三个字符,有时条目是四个字符。

文本文件条目示例:

  YYYY: AAA BBBB CCCC DDDD EEEE
        FFF GGG HHH III JJJ LLL

  ZZZZ: 111 2222 3333 4444 5555
        777 888 999 000 123 456

我正在使用 StreamReader。我对这一切有点陌生。非常感谢您对我的耐心等待。

这是最新的尝试。正是在这一点上,我意识到我不知道如何通过使用 space 作为指标来解析我一直在寻找的下一个 "thing." 来解析整行一会儿。我只是似乎没有在寻找合适的 topics\commands.

Do
    Dim line As String = Streamy.ReadLine
    Dim Model As String = ""

    If line.Contains("MODEL") Then
        Dim newModelData As New ModelData
        Model = line.Substring(6, 3)
        newModelData.Model = line.Substring(6, 3)

        If newModelData.Model = "   " Then
            line.Skip(1)
        Else
            ModelDataList.Add(newModelData)
        End If
    End If

    If line.Contains("YYYY") Then
        Dim newModelData As New ModelData
        newModelData.Model = Model
        'This part below is where I realized I don't understand 
        'how to parse the line.  I've searched online, but 
        'apparently I just don't know the right topic to search for.

        newModelData.SomeModelInfo = line.Substring(23, 3)

        ModelDataList.Add(newModelData)
    End If

    Loop Until Streamy.EndOfStream
    db.BulkInsertAll(ModelDataList)
    Streamy.Close()
 End Using

结束使用 结束子

您可以使用 .Split 方法分隔由 space 分隔的字符串 - 像这样:

Dim line As String = Streamy.ReadLine
Dim lineParts() As String() = line.Split(" "c)

这里发生的是 lineParts 被声明为字符串数组,= 符号后的代码位将字符串拆分为每一点 space 出现。

她的奇数位代码 - " "c is to make sure that " " 被视为字符类型而不是字符串类型。

您最终得到的是一个仅包含文本的数组。

如果行首或行尾有 space,则数组中的元素将是空的,其中没有任何内容。所以我建议您也使用 .Trim 方法。所以你的代码现在看起来像这样:

Dim line As String = Streamy.ReadLine
line = line.Trim(" "c)
Dim lineParts() As String() = line.Split(" "c)

现在您可以按照自己的方式处理 lineParts

的数组