StreamReader 从文本文件中读取一行并选择一个符合条件的单词

StreamReader to read a line from text file and pick a word that matches the criteria

我正在用 c# 编写程序以使用流 reader 读取文本文件。 有一行,上面写着 "The data set WORK.Test has 0 observations and 5 variables"。 流 reader 必须读完这一行,并根据观察的数量进入 "if else loop"。 .我如何使流 reader 选择 0 或不观察。

System.IO.StreamReader file = new System.IO.StreamReader(@FilePath);
List<String> Spec = new List<String>();
while (file.EndOfStream != true)
{
    string s = file.ReadLine();
    Match m = Regex.Match(s, "WORK.Test has");
    if (m.Success)
    {
        // Find the number of observations  
        // and send an email if there are more than 0 observations.
    }
}

我不清楚你想要达到什么目的。在您的示例中,您只想获取 "has" 和 "obervations" 之间的数字?你为什么不使用正则表达式? 顺便说一句,你提供的是错误的“。”匹配任何东西。您宁愿尝试 @"WORK\.Test has (.*) observations"

你应该修改你的 Regex.

C#Regexclass中,无论你在( )里面放什么,都会被捕获到一个组项中。因此,假设您的输入字符串看起来像您指定的除了数字之外的内容,您可以使用 \d+.

捕获观察结果和变量

\d - 搜索数字。

\d+ - 搜索一位或多位数字。

using (FileStream fs = new FileStream("File.txt", FileMode.Open, FileAccess.Read))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        while (!sr.EndOfStream)
        {
            var line = sr.ReadLine();
            var match = Regex.Match(line, @"WORK.Test has (\d+) observations and (\d+) variables");
            if (match.Success)
            {
                int.TryParse(match.Groups[1].Value, out int observations);
                int.TryParse(match.Groups[2].Value, out int variables);
                // Send EMail etc.
            }
        }
    }
}