0

I am using a string which contains a regex expression to validate an email, the email is validating properly,unless a "+" symbol is included in the email. if someone has a email id suppose like this "billgates+apple@gmail.com", so at this point my regex is not working itz giving me a invalid username message,for else email id itz working fine here is my regex

 string strPattern = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";

I tried using other regex which validates for special symbols but still i have the same error.

 string strPattern = "^[a-zA-Z0-9]+([a-zA-Z0-9_.\\$&-]+)*@[a-zA-Z0-9]+([a-zA-Z0-9_.\\$&-]+)*\\.([a-zA-Z0-9]{2,4})$";

if anyone can help out,it will be usefull,thanx

Safwan
  • 171
  • 1
  • 15

1 Answers1

0

Using something like this should work: ^([0-9a-zA-Z]([-.\\w\\+]*[0-9a-zA-Z\\+])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$.

This assumes that you can use the plus sign in the name, but not the domain. The email cannot start with a plus sign either. If it is made from one character, then, that character cannot be a plus either.

This code:

        string[] terms = new string[] {"bob@bobmail.com", "+@mail.com", "+bob@mail.com", "bob1+bob2@email.com", "bob1+@microsoft.com" };
        Regex regex = new Regex("^([0-9a-zA-Z]([-.\\w\\+]*[0-9a-zA-Z\\+])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$");
        foreach (string term in terms)
        {
            System.Console.WriteLine(regex.IsMatch(term));
        }
        System.Console.ReadKey();

Yields:

True
False
False
True
True

I do not know if you wish the result you are getting for the last case (bob1+@microsoft.com).

npinti
  • 51,070
  • 5
  • 71
  • 94