[英]Retrieve specific data in a text file
我有一個名為“ Games.txt”的文本文件,如下所示:
Call of Duty: 50
Assasins Creed: 23
Watch Dogs: 140
如果我想知道“刺客信條”的數量,我將如何獲得?
到目前為止我嘗試過的是:
我嘗試通過了解字符串的長度和長度來找到它。 然后閱讀該內容並刪除前15個字符(“ Assasins Creed:”),這將使我陷入:23.但這是一種非常糟糕的方法,它需要我知道確切的行。
有什么更好的解決方案?
如果只想使用Regex獲取“刺客信條”的值,則可以執行以下操作:
Dim contents As String = IO.File.ReadAllText(filePath)
Dim re As New Regex("(Assasins Creed):\s*(\d+)")
Dim m As Match = re.Match(contents)
If m.Success Then
Console.WriteLine($"The number of '{m.Groups(1).Value}' games is {m.Groups(2).Value}.")
End If
輸出:
The number of 'Assasins Creed' games is 23.
如果您需要檢索所有游戲的值,則可以將上面的代碼調整為以下形式:
Dim contents As String = IO.File.ReadAllText(filePath)
Dim re As New Regex("(.+):\s*(\d+)")
Dim matches As MatchCollection = re.Matches(contents)
For Each m As Match In matches
Console.WriteLine($"The number of '{m.Groups(1).Value}' games is {m.Groups(2).Value}.")
Next
輸出:
The number of 'Call of Duty' games is 50.
The number of 'Assasins Creed' games is 23.
The number of 'Watch Dogs' games is 140.
筆記:
filePath
替換為文本文件的實際路徑。 Imports System.Text.RegularExpressions
才能使用Regex
類。 進入這個游戲的過程可能很棘手,因為很多人都希望初學者進行自己的研究並理解它,然后再提供簡單的解決方案和解釋為什么起作用。 給絕對的初學者一個正則表達式聲明看起來更像是在發揮自己的自我,而不是提供幫助,因此,如果您正在尋找一個初學者不僅可以使用,而且還希望理解的解決方案(並可能在他們的其他地方再次使用)代碼),則可以像下面這樣使用split命令:
我相信,如果您導入System.IO
,則在此階段它比正則表達式有用。
'Place this at the top of the code block above the Class statement
Imports System.IO 'This provides access to File.ReadAllLines (Input/Output)
然后,您可以創建一個函數,該函數檢索所需的信息並返回如下結果:
''' <summary>
''' Returns the game value plus the index in the list
''' </summary>
''' <param name="FilePath">Full path of the file</param>
''' <param name="Game">Name of the game to return</param>
''' <param name="index">(Optional) Index of the position in the list (-1 if not found)</param>
''' <returns></returns>
Function GameValue(ByVal FilePath As String, ByVal Game As String, Optional ByRef Index As Integer = -1) As Integer
'This returns the file as an array of lines
Dim Lines() As String = File.ReadAllLines(FilePath)
'This loop will iterate through each item in the array
For i As Integer = 0 To Lines.Length - 1
'This turns each line into an array of name and value (either side of the colon + space)
Dim Segments() As String = Lines(i).Split({": "}, StringSplitOptions.None)
'This will bypass any blank lines or lines without ": "
If Segments.Length > 1 Then
'This tries to match the first segment against the name of the game
If Segments(0) = Game Then
'This handles a successful match
'Store the index of the position of the game in the list
Index = i
'Convert final value into Integer and return result
Return Convert.ToInt32(Segments(1))
End If
End If
Next i
'If no correct match for Game is found, 0 is returned
Return 0
End Function
當您要調用該函數時,可以通過單擊按鈕來執行此操作,例如:
Private Sub cmdApply_Click(sender As Object, e As EventArgs) Handles cmdApply.Click
'Specify the filename however you like
Dim f As String = "C:\ProgramData\game.txt"
'Specify the name of game however you like
Dim g As String = "Watch Dogs"
'Start an index at -1 (This will get modified by the function if the result is found)
Dim i As Integer = -1
'Use the function to return process a result (value)
Dim v As Integer = GameValue(f, g, i)
Console.WriteLine("Game: " & g)
Console.WriteLine("Value: " & v)
Console.WriteLine("Index: " & i)
End Sub
有時候,一旦真正研究如何做,簡單的事情實際上可能會變得非常復雜。 和大多數事情一樣,總有另一種解決方法。
如果您嘗試使用此代碼,則應該可以進行以下操作:
注意事項:
Game: xys
值不是數字,則可能會發生錯誤 ": "
則不會發生錯誤,因為我們對此進行了測試 Game.ToUpper
和Segments(0).ToUpper
將兩個值都轉換為大寫,以檢查是否要刪除大小寫敏感度是否匹配
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.