Search code examples
c#.netregexemail-validation

regex expression to validate email which includes a "+" symbol


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 "[email protected]", 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


Solution

  • 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[] {"[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]" };
            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 ([email protected]).