开发者

Compare a text file with a pattern of text in c#?

I have compared a text file with a pattern like ".." and i need to write only the distinct values in a text file...

while ((line 开发者_高级运维= file.ReadLine()) != null)
{
    foreach (Match match in Regex.Matches(line, @"(\w*)\.\."))
    {
        dest.WriteLine(match.Groups[1]);
    }

    counter++;
}

How to get the distinct values...Any suggestion?


Add matches to a list if they've not already been added? Or just keep a running list of what's already been added? Something like:

List<string> seen = new List<string>();
    string line = string.Empty;
    while ((line = file.ReadLine()) != null)
    {
        foreach (Match match in Regex.Matches(line, @"(\w*)\.\."))
        {
            if (!seen.Contains(line))
            {
                Console.WriteLine(line);
                seen.Add(line);
            }
        }
    }

edit: I interpreted what you were after here; if you really do want the match group value, replace line in the conditional block with match.Groups[1].Value ...


I recommend pushing your values into an array and using this to ignore duplicates:

ArrayList myValues = new ArrayList();

while ((line = file.ReadLine()) != null)
{
  foreach (Match match in Regex.Matches(line, @"(\w*)\.\."))
  {
    if(!myValues.Contains(match.Groups[1])) {
         myValues.Add(match.Groups[1]);
         dest.WriteLine(match.Groups[1]);
    }
  } 
  counter++;
}


How about you add the match.Group[1] to a HashSet?

HashSet<string> hs = new HashSet<string>();
string line = "insert into depdb..fin_quick_code_met..jjj..depdb..jjj";
foreach (Match match in Regex.Matches(line, @"(\w*)\.\."))
{
    hs.Add(match.Groups[1].ToString());
}
foreach (string item in hs)
    Console.WriteLine(item);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜