日期:2014-05-17  浏览次数:20402 次

在线等待:如何去掉正则表达式匹配结果中的重复项
我想用正则表达式提取收件箱中的发件人地址,但是有重复发件地址,我只需要一个,并且其他的用分号隔开存到临时字符串中,请问如何去掉匹配

结果中的重复项? 谢谢
//匹配规则
  private static readonly Lazy<Regex> s_EmailRegex = new Lazy<Regex>(() => new Regex(
  "([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1" +
  ",3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})",
  Options), true);

string text="a@aa.com, b@bb.com ,a@aa.com,c@cc.com,b@bb.com";

  MatchCollection matches = s_EmailRegex.Value.Matches(text);

  for (int i = 0; i < matches.Count; i++)
  //在输入字符串中找到所有匹配  
  {
  _emailcontainer = _emailcontainer + matches[i].Value + ";";
  }
1,希望最终_emailcontainer 存的是 a@aa.com;b@bb.com;c@cc.com;如何高效去掉重复的邮箱地址?

2,在扫描源文本的过程中用字符串存储最终的匹配的结果会不会存在溢出的情况? 请教还有哪些临时存储方案?用数据库怕频繁读写.

------解决方案--------------------
try...

C# code
            List<string> listMails = new List<string>();
            for (int i = 0; i < matches.Count; i++)
            //在输入字符串中找到所有匹配   
            {
                if (!listMails.Contains(matches[i].Value))
                {
                    listMails.Add(matches[i].Value);
                    _emailcontainer += matches[i].Value + ";";
                }
            }

------解决方案--------------------
C# code
            string str = "a@aa.com,b@bb.com,a@aa.com,c@cc.com,b@bb.com" + ",";
            Regex reg = new Regex(@"(([^,\s]+?@[^,\s]+?,).*?)\2");
            while (str != (str = reg.Replace(str, "$1"))) ;
            Console.WriteLine(str.Trim(','));            
            Console.ReadLine();
//a@aa.com,b@bb.com,c@cc.com