This piece of code will validate an email address.
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
Explanation:
^ marks the beginning of the sequence, $ marks the end:
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
In between are 4 sequences:
[\w-\.]+
Brackets "[]" surround the range. "\w-" matches a word or a hyphed. "\." matches a period. So, "\w-\." matches words and hyphens followed by periods. "+" matches one or more of the previous expressions.
@
This is the literal "@" symbol
([\w-]+\.)+
Parens "()" are used to group. "[\w-]+" is one or more "words" or hyphens. "\." matches a literal period. The trailing "+" matches one or more of this group
[\w-]{2,4}
"[\w-]" matches a "word" or a hyphen. "{2,4}" allows 2-4 characters in this word