Vb.net 提取字段长度

Vb.net 提取字段长度,vb.net,vb.net-2010,fixed-width,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) '

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

 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
问题是我不知道每个字段的长度。

有没有办法读取第一行并获得字段长度?

既然我找到了答案,我就把它贴在这里,以防有人会遇到同样的问题。
我用正则表达式解决了这个问题

'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
的rowdata是文件的第一行
Dim ParLength()作为整数=无”数组来存储长度
将正则表达式调整为新正则表达式(“[^\W\ud]+”_
RegexOptions.IgnoreCase_
或RegexOptions。多行_
或RegexOptions。单线_
或RegexOptions.ignorepattern(空格)
Dim myMatches As MatchCollection=regex.Matches(sRowData)
ReDim parlength(myMatches.Count-1)
对于我的匹配项,i=0。计数-1
将k变为整数
k=If(i

我希望有人会觉得它有用。

如果你有第一行,你会如何确定字段宽度?我找到了一种方法。阅读第一行,然后使用正则表达式查找长度。我将在周一发布解决方案。