VB.net 从以 开头的文本文件中读取特定行,并在以 开头时停止读取

VB.net Read Specific Lines From a Text File That Start With and Stop Reading When Start With

我想从文本文件中读取以特定字符开头并在该行以其他字符开头时停止的行。因此,在我的示例中,我想从 AB 行开始阅读并在 EF 行停止,但并非所有行都包含 CD 行。总会有AB线和EF线,但中间的线数未知。

这是我将要阅读的文本文件中的行示例。您可以看到这将在 DataGridView 中创建两行,但是第一行缺少 CD 行并且应该是空白的。

AB-id1
EF-address1
AB-id2
CD-name1
EF-address2

这是我目前的代码:

  Dim lines() As String = File.ReadAllLines(textfile)
    For i As Integer = 0 To lines.Length - 1
            If lines(i).StartsWith("AB") Then
            Dim nextLines As String() = lines.Skip(i + 1).ToArray
            
            Dim info As String = nextLines.FirstOrDefault(Function(Line) Line.StartsWith("CD"))
            Dim name As String = "Yes"
            
            Dim info2 As String = nextLines.FirstOrDefault(Function(Line) Line.StartsWith("EF"))
            Dim address As String = "Yes"
            End If

            DataGridView.Rows.Add(name,address)
    Next 

现在我目前得到的输出是:

|Yes|Yes|
|Yes|Yes|

我应该得到:

||Yes|
|Yes|Yes|

它似乎在文本文件中读得太远了,我需要它在 EF 停止阅读。我试过 Do while 和 Do Until 但没有成功。有什么建议吗?

您可以使用 Array.FindIndex 函数获取以您的前缀开头的下一行的索引。这样您就不必每次都跳过行并创建一个新数组。

试试这个:

Dim lines() As String = File.ReadAllLines(textFile)
For i As Integer = 0 To lines.Length - 1
    If lines(i).StartsWith("AB") Then
        Dim addressIndex As Integer = Array.FindIndex(lines, i + 1, Function(Line) Line.StartsWith("EF"))
        Dim address As String = If(addressIndex <> -1, lines(addressIndex).Substring(3), "") ' Get everything past the "-"

        Dim name As String = ""
        If addressIndex <> -1 Then
            Dim nameIndex As Integer = Array.FindIndex(lines, i + 1, addressIndex - i, Function(line) line.StartsWith("CD"))
            If nameIndex <> -1 Then
                name = lines(nameIndex).Substring(3) ' Get everything past the "-"
            End If
        End If

        DataGridView.Rows.Add(name, address)
    End If
Next