如何删除MatchCollection中的重复匹配项 [英] How to Remove Duplicate Matches in a MatchCollection

查看:446
本文介绍了如何删除MatchCollection中的重复匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MatchCollection中,我得到了同一件事的匹配项.像这样:

In my MatchCollection, I get matches of the same thing. Like this:

string text = @"match match match";
Regex R = new Regex("match");
MatchCollection M = R.Matches(text);

如何删除重复的匹配项,这是最快的方法吗?

How does one remove duplicate matches and is it the fastest way possible?

此处假定重复"表示匹配项包含完全相同的字符串.

推荐答案

Linq

如果您使用的是.Net 3.5或更高版本(例如4.7),则可以使用linq删除匹配项的重复项.

Linq

If you are using .Net 3.5 or greater such as 4.7, linq can be used to remove the duplicates of the match.

string data = "abc match match abc";

Console.WriteLine(string.Join(", ", 

Regex.Matches(data, @"([^\s]+)")
     .OfType<Match>()
     .Select (m => m.Groups[0].Value)
     .Distinct()

));

// Outputs abc, match


.Net 2或否Linq

将其放入hastable中,然后提取字符串:


.Net 2 or No Linq

Place it into a hastable then extract the strings:

string data = "abc match match abc";

MatchCollection mc = Regex.Matches(data, @"[^\s]+");

Hashtable hash = new Hashtable();

foreach (Match mt in mc)
{
    string foundMatch = mt.ToString();
    if (hash.Contains(foundMatch) == false)
        hash.Add(foundMatch, string.Empty);

}

// Outputs abc and match.
foreach (DictionaryEntry element in hash)
    Console.WriteLine (element.Key);

这篇关于如何删除MatchCollection中的重复匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆