检索文本文件中的特定数据

时间:2018-08-30 15:43:08

标签: vb.net

我有一个名为“ Games.txt”的文本文件,如下所示:

Call of Duty: 50
Assasins Creed: 23
Watch Dogs: 140

如果我想知道“刺客信条”的数量,我将如何获得?

到目前为止我尝试过的事情:

我试图通过了解字符串的长度和长度来找到它。然后阅读该内容并删除前15个字符(“ Assasins Creed:”),这将使我陷入:23.但这是一种非常糟糕的方法,它需要我知道确切的行。

什么是更好的解决方案?

2 个答案:

答案 0 :(得分:0)

如果只想使用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类。

答案 1 :(得分:0)

开始玩这个游戏可能很棘手,因为很多人都希望初学者进行自己的研究并理解它,然后再提供一个简单的解决方案和解释为什么起作用。给绝对的初学者一个正则表达式声明看起来更像是在发挥自己的自我,而不是提供帮助,所以,如果您正在寻找一个初学者不仅可以使用的解决方案,而且还希望理解(并可能在他们的其他地方再次使用)代码),那么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

有时候,一旦真正研究如何做,简单的事情实际上可能会变得非常复杂。和大多数事情一样,总有另一种解决方法。

如果您尝试使用此代码,则应该可以清除以下内容:

  • 如何制作和使用功能
  • 如何在函数中添加xml标记,以使其易于理解
  • 一种利用ByRef来影响在其他地方声明的变量(索引)的值的方法
  • 如何阅读文本文件并处理其内容
  • 如何将字符串拆分为数组以进行独立处理
  • 如何将字符串转换为整数

注意事项:

  • 如果文件路径或名称不存在,将发生错误
  • 如果Game: xys的值不是数字,则可能会发生错误
  • 如果该行不包含": ",则会发生错误,因为我们对此进行了测试
  • 在这种情况下,游戏名称​​ 区分大小写。如果要删除区分大小写,可以在检查它们是否匹配时使用Game.ToUpperSegments(0).ToUpper将两个值都转换为大写。