我需要帮助减少代码。我必须检查两个不同的maches并且需要将它们存储在同一个matchcollection中。我不知道怎么做,这是我的代码,任何人都可以帮我这样做。
var patternEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
MatchCollection emailCollection1;
//Get emails from ResponsibleConsultant
emailCollection1 = Regex.Matches(piWorkitem.ResponsibleConsultant, patternEmail);
foreach (Match mail in emailCollection1.Cast<Match>().Where(mail => !emailaddresses.Contains(mail.Value.ToString())))
{
emailaddresses.Add(mail.Value);
}
MatchCollection emailCollection2;
//Get emails from ResponsibleConsultant
emailCollection2 = Regex.Matches(piWorkitem.SupplierConsultant, patternEmail);
foreach (Match mail in emailCollection2.Cast<Match>().Where(mail => !emailaddresses.Contains(mail.Value.ToString())))
{
emailaddresses.Add(mail.Value);
}
帮助我避免多次重复代码。
答案 0 :(得分:2)
var patternEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
var allInput = piWorkitem.ResponsibleConsultant + " " + piWorkitem.SupplierConsultant;
var emailCollection = Regex.Matches(allInput , patternEmail);
foreach (Match mail in emailCollection.Cast<Match>().Where(mail => emailaddresses.Contains(mail.Value.ToString())))
{
emailaddresses.Add(mail.Value);
}
答案 1 :(得分:0)
您可以使用Union
加入两个结果试试这个:
var patternEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
var emailCollection1 = Regex.Matches(piWorkitem.ResponsibleConsultant, patternEmail).Cast<Match>().Union(Regex.Matches(piWorkitem.SupplierConsultant, patternEmail).Cast<Match>());
foreach (Match mail in emailCollection1.Where(mail => !emailaddresses.Contains(mail.Value.ToString())))
{
emailaddresses.Add(mail.Value);
}
答案 2 :(得分:0)
private void TestFunc()
{
var patternEmail = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
var all = ExtactMatches(patternEmail, piWorkitem.SupplierConsultant, piWorkitem.ResponsibleConsultant);
}
private IEnumerable<string> ExtactMatches(string pattern, params string[] srcText)
{
HashSet<string> emailaddresses = new HashSet<string>();
foreach (var text in srcText)
{
//Get emails from ResponsibleConsultant
var emailCollection1 = Regex.Matches(text, pattern);
foreach (Match mail in emailCollection1.Cast<Match>().Where(mail => !emailaddresses.Contains(mail.Value.ToString(CultureInfo.InvariantCulture))))
{
emailaddresses.Add(mail.Value);
}
}
return emailaddresses;
}