Dheeraj Sharma
Dheeraj Sharma

Reputation: 13

To search and return for unique string value counts in C# through input text file?

I have a log file in the following format :

INFO [SearchServices] WX Search = Server:nomos-scanner.corp.adobe.com User:ashishg appGUID: wx Elapsed Time:875ms SaveSearchID:361
INFO [SearchServices] WX Search = Server:nomos-scanner.corp.adobe.com User:ashishg appGUID: wx Elapsed Time:875ms SaveSearchID:361
INFO [SearchServices] WX Search = Server:nomos-scanner.corp.adobe.com User: ashishg appGUID: wx Elapsed Time:875ms SaveSearchID:361
INFO [SearchServices] WX Search = Server:nomos-scanner.corp.adobe.com User:karansha appGUID: wx Elapsed Time:875ms SaveSearchID:361
INFO [SearchServices] WX Search = Server:nomos-scanner.corp.adobe.com User:gulanand appGUID: wx Elapsed Time:875ms SaveSearchID:361
INFO [SearchServices] WX Search = Server:nomos-scanner.corp.adobe.com User:ashishg appGUID: wx Elapsed Time:875ms SaveSearchID:361

Code that I have tried is :

StreamReader reader = new StreamReader("test file path");     
string x = reader.ReadToEnd();

List<string> users = new List<string>();
int numberOfUsers;

Regex regex = new Regex(@"User:(?<username>.*?) appGUID");
MatchCollection matches = regex.Matches(x);

foreach (Match match in matches)
{
    if (!users.Contains(match.ToString())) users.Add(match.ToString());
}

Regex regex2 = new Regex(@"User: (?<username>.*?) appGUID");
matches = regex2.Matches(x);

foreach (Match match in matches)
{
    if (!users.Contains(match.ToString())) users.Add(match.ToString());
}

numberOfUsers = users.Count;
Console.WriteLine(numberOfUsers);
// keep screen from going away
// when run from VS.NET`

Upvotes: 1

Views: 168

Answers (1)

Oscar Mederos
Oscar Mederos

Reputation: 29813

See the below code:

StreamReader reader = new StreamReader(@"test file path");
string x = reader.ReadToEnd();
List<string> users = new List<string>();
Regex regex = new Regex(@"User:\s*(?<username>.*?)\s+appGUID");
MatchCollection matches = regex.Matches(x);
foreach (Match match in matches) {
    var user = match.Groups["username"].Value;
    if (!users.Contains(user)) users.Add(user);
}
int numberOfUsers = users.Count;
Console.WriteLine(numberOfUsers);

I did the following two modifications:

  1. You don't need two regular expressions. I edited it to cover both cases
  2. You were accessing to the match, but in order to get the username, you should be accessing to the username group.

Upvotes: 2

Related Questions