在大型文本文件中的字符串中查找子字符串的最后一次出现

Find the last occurrence of substring in string in a large text file

我正在尝试通读一个巨大的文本文件,大约 10 GB。 我想找到最后一次出现的字符串。

例如下面是 5 行的示例,第 2 行和第 5 行是相同的字符串。
我想使用最后一个,因为它是最新的,并使用 streamreader 将其输出到文本文件。

我最好使用 Regex 还是使用 lastindexof 来确定它是否是最后一个字符串?

我有很多这样的搜索要做,所以我会创建某种数组并让它从下到上搜索以提高性能。

有人能指出我正确的方向吗?

GET/a/users/115656WindowsNT6.1;Trident
GET/a/users/126692MSIE7.0;WindowsNT6.1
GET/a/users/77562WindowsNT6.1;WOW64;Tr
GET/a/users/35650WindowsNT6.1;WOW64;Tr
GET/a/users/126692MSIE7.0;WindowsNT6.2

我相信 File.ReadLines 是根据 msdn 读取大文件的最佳方法之一:

The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

所以根据这个我写了下面的代码,希望对你有帮助:

Dim myList As List(Of String) = IO.File.ReadLines("MyLargFile.txt").OfType(Of String)().Where(Function(s) s.Contains("126692MSIE7")).ToList

这段代码会return你一个匹配字符串行的列表。

输出:

myList(0) = "GET/a/users/126692MSIE7.0;WindowsNT6.1" 
myList(1) = "GET/a/users/126692MSIE7.0;WindowsNT6.2"

当然,如果需要最后一行,您可以使用 Last 方法:

Dim last As String = myList.Last