Find all email addresses in a string using regex i

2019-09-20 00:01发布

I have some characters in a string. I would like to find all email addresses from this string and find index also.

mytext= "My mail id is grk@gmail.com and my friend mail id is newxyz@yahoo.com";

Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$  ");
Match match = regex.Match(mytext);
if (match.Success) {
    TextBox1.Text = match.Value;
    int IndexValue=match.Index;
}
match = match.NextMatch();
if (match.Success) {
    TextBox2.Text = match.Value;
    int IndexValue=match.Index;
}

标签: c# regex
2条回答
对你真心纯属浪费
2楼-- · 2019-09-20 00:25

This works...

var mytext = "My mail id is grk@gmail.com and my friend mail id is newxyz@yahoo.com";

Regex regex = new Regex(@"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])");
Match match = regex.Match(mytext);
if (match.Success)
{
    TextBox1.Text = match.Value;
    int IndexValue = match.Index;
}
match = match.NextMatch();
if (match.Success)
{
    TextBox2.Text = match.Value;
    int IndexValue = match.Index;
}

Please refer to http://emailregex.com/ for more details.

查看更多
聊天终结者
3楼-- · 2019-09-20 00:44

Try following code snippet. Regex taken from

void Main()
{
    string pattern = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";

    string input = @"My mail id is grk@gmail.com and my friend mail id is newxyz@yahoo.com";

    var m = Regex.Match(input, pattern);
    if (m.Success)
    {
        Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
    }
    m = m.NextMatch();
    if (m.Success)
    {
        Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
    }

}

// Define other methods and classes here
查看更多
登录 后发表回答