Reputation: 69
I'm writing a a program in c# to read through the text file using stream reader. There is a line , which says "The data set WORK.Test has 0 observations and 5 variables". The stream reader has to read through this line, and get into an "if else loop" based on the number of Observations. . How i can make the stream reader pick on 0 or not observations.
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.
}
}
Upvotes: 0
Views: 1569
Reputation: 10393
You should modify your Regex
.
In C#
Regex
class, whatever you put inside ( )
will be captured into a group item. So assuming your input sting looks like what you've specified except for the numbers, you can capture observations and variables by using \d+
.
\d
- Searches for a digit.
\d+
- Searches for one or more digits.
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.
}
}
}
}
Upvotes: 0
Reputation: 1041
It is not clear to me what you want to achieve. In your example, you want to get only the number between "has" and "obervations"? Why do you not use Regex?
Btw the one you provided is wrong as "." matches anything. You rather should try @"WORK\.Test has (.*) observations"
Upvotes: 0