c# - 如何使用 C# Regex 获取最后一场比赛

标签 c# regex

我正在尝试使用正则表达式使用以下代码读取大型文本文件中的最后一个序列号。文本文件中每行文本开头的序列号前后各有两个空格。如果文件太大,这需要相当长的时间。是否可以从文件末尾读取文本文件到开头,以便单独使用 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/

相关文章:

c# - 使用 yield return 的强类型方法接口(interface)

c# - ExecuteNonQuery 离开休眠等待命令 session

python - 使用文本文件中的正则表达式在 Python 中的特定单词后查找单词

regex - 如何将变量插入正则表达式 .match() 断言中?

php - 使用正则表达式验证电子邮件地址

c# - WPF:我在哪里可以捕获应用程序崩溃事件?

c# - 在文本框中从右到左输入?

C# 6.0 多个相同的空条件运算符检查与单个传统检查

java - Pattern matcher.group() 越界异常

忽略子字符串的 JavaScript 正则表达式