首页 > 解决方案 > 使用 c# 从文本字符串中查找并提取所有电子邮件地址

问题描述

有没有办法使用 C# 从纯文本中提取所有电子邮件地址。

例如这个字符串:

[id=4068;name=mrgar@yahoo.com]
[id=4078;name=mrrame@gmail.com]

应该返回

mrrame@gmail.com, mrgar@yahoo.com

我尝试了以下代码但没有成功。

拜托,你能帮帮我吗?

protected void btnFinal_Click(object sender, EventArgs e)
{
    JavaScriptSerializer jsSer = new JavaScriptSerializer();
    object obj = jsSer.DeserializeObject(hidJsonHolder.Value);
    Movie[] listMovie = jsSer.ConvertToType<Movie[]>(obj);
    foreach (Movie p in listMovie)
    {
        txta.Text += p.ToString();
        const string MatchEmailPattern =
       @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
       + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
         + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
       + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
        Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        MatchCollection matches = rx.Matches(p.ToString());
        int noOfMatches = matches.Count;
        foreach (Match match in matches)
        {
            Response.Write(p.ToString() + "<br />");
        }
    }
}

标签: listemail

解决方案


我认为基本上你已经正确regular expression地从文本中提取所有电子邮件地址。

但是,问题是您没有正确使用它。

正确的步骤如下:

用于regular express (Regex)匹配文本。

对于 中的每个匹配结果MatchCollection,从匹配结果中获取值。

为了Regular expression更清楚,我将所有Regex方法都放在额外的方法中,您可以单独调用这些方法来提取电子邮件。

所有代码都是根据您的原始代码编写的。

更多细节,你可以参考下面的代码。

.aspx 页面:

 <form id="form1" runat="server">
        <div>
            <h1>This is Page</h1>
            <asp:Button ID="btnFinal" runat="server" Text="Click" OnClick="btnFinal_Click" />
            <br />
            <asp:Label ID="displayLabel" runat="server"></asp:Label>
        </div>
    </form>

代码背后:

protected void btnFinal_Click(object sender, EventArgs e)
{
    string exampleTxt = @"[id=4068;name=mrgar@yahoo.com][id=4078;name=mrrame@gmail.com]";
    string[] emails = identifyEmailAddress(exampleTxt);
    foreach (string s in emails)
    {
        displayLabel.Text += s + "<br />";
    }
}

private string[] identifyEmailAddress(string txt)
{    
    const string MatchEmailPattern = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
    Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    MatchCollection matches = rx.Matches(txt);
    int noOfMatches = matches.Count;
    string[] result = new string[noOfMatches];
    int i = 0;
    foreach (Match match in matches)
    {
        result[i++] = match.Value.ToString();
    }

    return result;
}

演示:


推荐阅读