要通过输入文本文件在C#中搜索并返回唯一字符串值计数?

时间:2013-02-27 09:57:05

标签: c#

我有以下格式的日志文件:

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

我尝试的代码是:

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`

1 个答案:

答案 0 :(得分:2)

见下面的代码:

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);

我做了以下两个修改:

  1. 您不需要两个正则表达式。我编辑它以涵盖两种情况
  2. 您正在访问该匹配项,但为了获取用户名,您应该访问username