1

コードを最小化するのに助けが必要です。2 つの異なるマッチをチェックする必要があり、両方を同じ 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);
}

コードを複数回繰り返さないようにしてください。

4

3 に答える 3

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);
}
于 2013-02-20T06:20:18.057 に答える
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);
    }
于 2013-02-20T06:13:10.913 に答える
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;
    }
于 2013-02-20T06:17:03.007 に答える