我正在尝试使用正则表达式使用以下代码读取大型文本文件中的最后一个序列号。文本文件中每行文本开头的序列号前后各有两个空格。如果文件太大,这需要相当长的时间。是否可以从文件末尾读取文本文件到开头,以便单独使用 Match 进行第一次捕获即可得到答案并减少在 c# 中花费的时间。提前致谢。
string contents = File.ReadAllText(path);
string pattern = @"(?<=\s{2}\d{1,7}(?=\s{2})";
MatchCollection matches = Regex.Matches(contents, pattern);
string lastmatch = string.Empty;
foreach (Match s in matches)
{
lastmatch = s.Groups[0].ToString();
}
MessageBox.Show(lastmatch);
文本文件看起来像。
1 Blah Blah Blah.
2 Ding Dong Bell.
3 Hello, how are you.
4 My name is Unnikrishnan.
5 You are a very good friend.
最佳答案
为了我的目的,我如何调整在堆栈溢出中找到的答案是这样的。在我的例子中,特定的文本文件大小为 75 MB。我想检查更大的文件。任何文件大小,我都会在眨眼之间得到答案。
public int w { get; set; }
public void determineSizeOfFile()
{
//Not used at present. Designed to count the no. of serial no. of items in the file.
using (var reader = new StreamReader(fileToProcess)) //Remarkable solution learnt from stack overflow.
{
if (reader.BaseStream.Length > 1024)
{
reader.BaseStream.Seek(-60000, SeekOrigin.End);
}
string line;
string lastmatch = string.Empty;
while ((line = reader.ReadLine()) != null)
{
string pattern = @"(?<=\s{2})\d{1,7}(?=\s{2})";
Match match = Regex.Match(line, pattern);
if (match.Success)
{
lastmatch = match.Value;
w = Convert.ToInt32(lastmatch);
}
}
}
}
关于c# - 如何使用 C# Regex 获取最后一场比赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33317132/