Original Source: RegexLib.com
After modification, two new features are added:
1. match a format containing a name like "lc <deerchao@xxx.com>.
2. Four naming groups are added: name, email, user, and domain. This allows you to conveniently retrieve the corresponding information.
Regex re = new Regex (@ "^ ((? 'Name'. + ?) \ S * <)? (? 'Email '(?> [A-zA-Z \ d! # $ % & '* + \-/=? ^ _ '{|} ~] + \ X20 * | ""(? 'User '(? = [\ X01-\ x7f]) [^ "" \] | \ [\ x01-\ x7f]) * "" \ x20 *)*(? 'Angle '<))? (? 'User '(?! \.) (?> \.? [A-zA-Z \ d! # $ % & '* + \-/=? ^ _ '{|} ~] +) + | ""((? = [\ X01-\ x7f]) [^ "" \] | \ [\ x01-\ x7f]) * ") @ (? 'Domain '((?! -) [A-zA-Z \ d \-] + (? <! -) \.) + [A-zA-Z] {2,} | \[(((? (? <! \ [) \.) (25 [0-5] | 2 [0-4] \ d | [01]? \ D? \ D) {4} | [a-zA-Z \ d \-] * [a-zA-Z \ d] :( (? = [\ X01-\ x7f]) [^ \ [\] | \ [\ x01-\ x7f]) +) \] (? 'Angle ')(? (Name)>) $ ", RegexOptions. Multiline | RegexOptions. ExplicitCapture );
MatchCollection mc = re. Matches (@ "l c <abc@example.com>
Abc@example.com
ABC@example.com
Abc.123@example.com
");
Foreach (Match ma in mc)
{
}
The biggest advantage of the original expression is its powerful matching capability. It can meet various expressions that comply with the specifications (RFC2882.
Match the 10/11 valid email address formats on WikiPedia. The invalid one does not match either of the following:
Valid e-mail addresses
- Abc@example.com
- Abc@example.com
- ABC@example.com
- Abc.123@example.com
- 1234567890@example.com
- _______ @ Example.com
- Abc+ mailbox/department = shipping@example.com
-
! # $ % & '* +-/=? ^ _ '. {| }~ @ Example.com (all of these characters are allowed)
- "Abc @ def" @ example.com (anything goes inside quotation marks)
- "Fred Bloggs" @ example.com
- "% () [] \;:, <>" @ Example.com
Invalid e-mail addresses
-
Abc.example.com (character @ is missing)
-
Abc.@example.com (character dot (.) is last in local part)
-
Abc..123@example.com (character dot (.) is double)
-
A @ B @ c@example.com (only one @ is allowed outside quotations marks)
-
% () [] \;:, <> @ Example.com (none of the characters before the @ is allowed outside quotation marks)