提取字段长度

时间:2014-08-15 15:14:49

标签: vb.net vb.net-2010 fixed-width

我想阅读固定长度的文件 如果我知道场长,我知道怎么做。

 Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(filePath)

        Reader.TextFieldType =
        Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
        Reader.SetFieldWidths(8, 16, 16, 12, 14, 16) 'They are different in each file

        Dim currentRow As String()
        While Not Reader.EndOfData
            Try
                currentRow = Reader.ReadFields()
                Dim currentField As String
                For Each currentField In currentRow
                    MsgBox(currentField)
                Next
            Catch ex As Microsoft.VisualBasic.
                        FileIO.MalformedLineException
                MsgBox("Line " & ex.Message &
                "is not valid and will be skipped.")
            End Try
        End While
    End Using

问题在于我不知道每个领域的长度 有没有办法读取第一行并获得字段长度?

1 个答案:

答案 0 :(得分:0)

由于我找到了答案,我将在此处发布,以防有​​人遇到同样的问题。
我用正则表达式解决了它

'sRowData is the first line of the file
 Dim pArLengths() As Integer = Nothing 'Array to store the lengths

 Dim regex As New Regex("[^\W_\d]+", _
                        RegexOptions.IgnoreCase _
                        Or RegexOptions.Multiline _
                        Or RegexOptions.Singleline _
                        Or RegexOptions.IgnorePatternWhitespace)

 Dim myMatches As MatchCollection = regex.Matches(sRowData)

 ReDim pArLengths(myMatches.Count - 1)

 For i = 0 To myMatches.Count - 1
     Dim k As Integer
     k = If(i < myMatches.Count - 1, myMatches(i + 1).Index, sRowData.Length)
     pArLengths(i) = k - myMatches(i).Index
 Next

我希望有人能发现它有用。