Vb.net 读取.txt文件

Vb.net 读取.txt文件,vb.net,Vb.net,我使用以下代码从.txt文件中读取文本。但我不知道该怎么做 在文件中执行搜索,以及如何根据搜索读取文本文件中的特定行 Dim vrDisplay = My.Computer.FileSystem.ReadAllText(CurDir() & "\keys.txt") MsgBox(vrDisplay) 比如, 如果我想读包含“开始”一词的那一行,怎么做 谢谢。从您的帖子中很难判断这是否是最好的解决方案,但有一种解决方案可以用来查找包含单词Start的所有行: ^.*\bStar

我使用以下代码从.txt文件中读取文本。但我不知道该怎么做 在文件中执行搜索,以及如何根据搜索读取文本文件中的特定行

Dim vrDisplay = My.Computer.FileSystem.ReadAllText(CurDir() & "\keys.txt")
    MsgBox(vrDisplay)
比如,

如果我想读包含“开始”一词的那一行,怎么做


谢谢。

从您的帖子中很难判断这是否是最好的解决方案,但有一种解决方案可以用来查找包含单词
Start的所有行:

^.*\bStart\b.*$
匹配包含完整单词的整行
Start
任意位置。它拒绝将
开始
作为单词的一部分,例如
开始
将不匹配(这就是
\b
单词边界锚的作用)

要在VB.NET中使用此选项,请执行以下操作:

Dim RegexObj As New Regex(
    "^      # Start of line" & chr(10) & _
    ".*     # Any number of characters (anything except newlines)" & chr(10) & _
    "\b     # Word boundary" & chr(10) & _
    "Start  # ""Start""" & chr(10) & _
    "\b     # Word boundary" & chr(10) & _
    ".*     # Any number of characters (anything except newlines)" & chr(10) & _
    "$      # End of line", 
    RegexOptions.Multiline Or RegexOptions.IgnorePatternWhitespace)
AllMatchResults = RegexObj.Matches(vrDisplay)
If AllMatchResults.Count > 0 Then
    ' Access individual matches using AllMatchResults.Item[]
Else
    ' Match attempt failed
End If

从您的帖子中很难判断这是否是最好的解决方案,但有一种解决方案是查找包含单词
Start
的所有行:

^.*\bStart\b.*$
匹配包含完整单词的整行
Start
任意位置。它拒绝将
开始
作为单词的一部分,例如
开始
将不匹配(这就是
\b
单词边界锚的作用)

要在VB.NET中使用此选项,请执行以下操作:

Dim RegexObj As New Regex(
    "^      # Start of line" & chr(10) & _
    ".*     # Any number of characters (anything except newlines)" & chr(10) & _
    "\b     # Word boundary" & chr(10) & _
    "Start  # ""Start""" & chr(10) & _
    "\b     # Word boundary" & chr(10) & _
    ".*     # Any number of characters (anything except newlines)" & chr(10) & _
    "$      # End of line", 
    RegexOptions.Multiline Or RegexOptions.IgnorePatternWhitespace)
AllMatchResults = RegexObj.Matches(vrDisplay)
If AllMatchResults.Count > 0 Then
    ' Access individual matches using AllMatchResults.Item[]
Else
    ' Match attempt failed
End If

为了提高效率,不必阅读所有文本

  • 为有问题的文件打开文件流
  • 创建一个StreamReader
  • 循环,调用ReadLine,直到找到文件的结尾或字符串包含“Start”


编辑:即使需要将整个文件保存在内存中,为了提高效率,您仍然可以通过使用
MemoryStream()

而不是读取所有文本来执行上述操作

  • 为有问题的文件打开文件流
  • 创建一个StreamReader
  • 循环,调用ReadLine,直到找到文件的结尾或字符串包含“Start”


编辑:即使需要将整个文件保存在内存中,也可以通过使用
MemoryStream()

来执行上述操作,但是内置的StreamReader.ReadLine()可能比在包含整个文件的字符串上运行正则表达式更快,所需内存更少。@Reinderien:没错。但他可能需要立即将整个文件存储在内存中。谁能说呢?可能可以,但是内置StreamReader.ReadLine()可能比在包含整个文件的字符串上运行正则表达式更快,所需内存更少。@Reinderien:没错。但他可能需要立即将整个文件存储在内存中。谁知道呢?