const regex = /^[a-z]{1}[a-z0-9!#$%&'*+-\/=?^_`{|}~]{0,}@[a-z]{1}[a-z.0-9-]{0,}[a-z0-9]{1}\.[a-z0-9]{2,}$/gim;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^[a-z]{1}[a-z0-9!#$%&\'*+-\\\/=?^_`{|}~]{0,}@[a-z]{1}[a-z.0-9-]{0,}[a-z0-9]{1}\\.[a-z0-9]{2,}$', 'gim')
const str = `opinionated email validation based on https://en.wikipedia.org/wiki/Email_address
Valid email addresses
simple@example.com
werw@mydomain.gov.us
very.common@example.com
very.co34mmon@example.com
disposable.style.email.with+symbol@example.com
other.email-with-hyphen@example.com
other.email-with-hyphen@ex12ample.com
other.email-with-hyphen@exa-mple.com
fully-qualified-domain@example.com
example-indeed@strange-example.com
Invalid email addresses
user-@example.org (local part ending with non-alphanumeric character from the list of allowed printable characters)
x@example.com (one-letter local-part)
admin@mailserver1 (local domain name with no TLD, although ICANN highly discourages dotless email addresses[10])
user.name+tag+sorting@example.com (may go to user.name@example.com inbox depending on mail server)
user%example.com@example.org (% escaped mail route to user@example.com via example.org)
mailhost!username@example.org (bangified host route used for uucp mailers)
example@s.example (see the List of Internet top-level domains)
@example.org (space between the quotes)
john..doe@example.org (quoted double dot)
Abc.example.com (no @ character)
A@b@c@example.com (only one @ is allowed outside quotation marks)
a"b(c)d,e:f;g<h>i[j\\k]l@example.com (none of the special characters in this local-part are allowed outside quotation marks)
just"not"right@example.com (quoted strings must be dot separated or the only element making up the local-part)
this is"not\\allowed@example.com (spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash)
this\\ still\\"not\\\\allowed@example.com (even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes)
1234567890123456789012345678901234567890123456789012345678901234+x@example.com (local-part is longer than 64 characters)
i_like_underscore@but_its_not_allowed_in_this_part.example.com (Underscore is not allowed in domain part)`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions