4.1. Validate Email Addresses
Problem
You have a form on your website or a dialog box in your application that asks the user for an email address. You want to use a regular expression to validate this email address before trying to send email to it. This reduces the number of emails returned to you as undeliverable.
Solution
Simple
This first solution does a very simple check. It only validates that the string contains an at sign (@) that is preceded and followed by one or more nonwhitespace characters.
^\S+@\S+$
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python |
\A\S+@\S+\Z
| Regex options: None |
| Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby |
Simple, with restrictions on characters
The domain name, the part after the @ sign, is restricted to characters allowed in domain names. Internationalized domain names are not allowed. The local part, the part before the @ sign, is restricted to characters commonly used in email local parts, which is more restrictive than what most email clients and servers will accept:
^[A-Z0-9+_.-]+@[A-Z0-9.-]+$
| Regex options: Case insensitive |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python |
\A[A-Z0-9+_.-]+@[A-Z0-9.-]+\Z
| Regex options: Case insensitive |
| Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby |
Simple, with all valid local part characters
This regular expression expands the previous one by allowing a larger set of rarely used characters in the local part. Not all email software can handle all these characters, but we’ve included ...