-1

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;
}
dda
  • 6,030
  • 2
  • 25
  • 34
Ram
  • 41
  • 1
  • 9
  • 3
    Fine and what is your question? – Sir Rufo Dec 29 '17 at 07:54
  • Why is there two spaces after `$` in your regex pattern ? – Pac0 Dec 29 '17 at 07:59
  • 2
    Possible duplicate of [How to validate email address in JavaScript?](https://stackoverflow.com/questions/46155/how-to-validate-email-address-in-javascript) **-edit-** *I know its not C# but the answers contain the regex that you need* – EpicKip Dec 29 '17 at 08:13

2 Answers2

1

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.

pmcilreavy
  • 3,076
  • 2
  • 28
  • 37
0

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
santosh singh
  • 27,666
  • 26
  • 83
  • 129