自從上次我做的時候在這里發布另一個問題,回答的人非常有幫助。請記住,我對 VB.net 比較陌生。
所以我正在開發一個程式,該程式使用 Regex.Split 從文本檔案中提取第一列和第三列,以消除檔案中字母數字字符之間的多個空格。
文本檔案外觀的高級示例如下:
VARIABLE1 MEAS1 STORAGE1
VARIABLE2 MEAS2 STORAGE2
VARIABLE3 MEAS3 STORAGE3
VARIABLE4 MEAS4 STORAGE4
VARIABLE5 MEAS5 STORAGE5
VARIABLE6 MEAS6 STORAGE6
#VARIABLE7 MEAS7 STORAGE7
VARIABLE8 MEAS8 STORAGE8
VARIABLE9 MEAS9 STORAGE9
VARIABLE10 MEAS10 STORAGE10
VARIABLE11 MEAS11 STORAGE11
VARIABLE12 MEAS12 STORAGE12
VARIABLE13 MEAS13 STORAGE13
VARIABLE14 MEAS14 STORAGE14
該檔案使用“#”來表示檔案中的注釋,因此在我的代碼中我告訴 System.IO 忽略該字符。但是,當創建一個測驗函式來嘗試這個時,我不斷得到一個索引越界錯誤,(僅在某些檔案上。由于某種原因,這種格式的一些作業正常)在查看執行輸出時,我收到錯誤在它寫入“STORAGE6”行之后,因此從 STORAGE6 遍歷到 VARIABLE7 時肯定會出現錯誤,我無法弄清楚。對此的任何見解將不勝感激!
我寫的測驗函式如下:
Public Function Testing()
OpenFileDialog1.ShowDialog()
Dim file = System.IO.File.ReadAllLines(OpenFileDialog1.FileName)
For Each line In file
Dim arrWords() As String = System.Text.RegularExpressions.Regex.Split(line, "\s ")
Dim upBound = arrWords.GetUpperBound(0)
If upBound <> 0 Then
If line.Contains("#") Or line.Length = 0 Then
Else
Console.WriteLine(arrWords(0) " " arrWords(2))
End If
End If
Next
End Function
我在呼叫“arrWords(2)”時遇到越界錯誤,我確信這很明顯,但只是試圖使問題盡可能詳細。
uj5u.com熱心網友回復:
簡單的修復是更改這兩行:
If upBound <> 0 Then
If line.Contains("#") Or line.Length = 0 Then
像這樣:
If upBound > 0 Then
If line.TrimStart().StartsWith("#") OrElse String.IsNullOrWhitespace(line) Then
但我真的會做更多這樣的事情:
Public Class DataItem
Public Property Variable As String
Public Property Measure As String
Public Property Storage As String
End Class
Public Function ReadDataFile(fileName As String) As IEnumerable(Of DataItem)
Return File.ReadLines(fileName).
Where(Function(line) Not line.TrimStart().StartsWith("#") AndAlso Not String.IsNullorWhitespace(line)).
Select(Function(line) System.Text.RegularExpressions.Regex.Split(line, "\s ")).
Where(Function(fields) fields.Length = 3).
Select(Function(fields)
Return New DataItem With {
.Variable = fields(0),
.Measure = fields(1),
.Storage = fields(2)}
End Function)
End Function
Public Function Testing()
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Dim records = ReadDataFile(OpenFileDialog1.FileName)
For Each record in records
Console.WriteLine($"{record.Variable} {record.Storage}")
Next
End If
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/314899.html
