我正在用c#编写一个程序,用流读取器读取文本文件。有一行写着“数据集WORK.Test有0个观察值和5个变量”。流阅读器必须读完这一行,并根据观察值的数量进入"if else循环“。。我如何让流阅读器选择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.
}
}发布于 2018-07-27 04:33:20
您应该修改您的Regex。
在C# Regex类中,您放在( )中的任何内容都将被捕获到一个组项目中。因此,假设除了数字之外,您的输入字符串与您指定的值类似,您可以使用\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.
}
}
}
}发布于 2018-07-27 04:31:40
我不清楚你想要实现什么。在您的示例中,您想只获取"has“和"obervations”之间的数字吗?为什么不使用Regex?顺便说一句,你提供的是错误的“。匹配任何东西。您应该尝试使用@"WORK\.Test has (.*) observations"
https://stackoverflow.com/questions/51546676
复制相似问题