const regex = /^([a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^([a-zA-Z0-9!#$%&\'*+\\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&\'*+\\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$', 'gm')
const str = `--------- valid ---------
something@something.com
someone@localhost.localdomain
someone@127.0.0.1
a@b.b
a/b@domain.com
{}@domain.com
m*'!%@something.sa
tu!!7n7.ad##0!!!@company.ca
%@com.com
!#\$%&'*+/=?^_\`{|}~.-@com.com
USER@EXAMPLE.COM
someone@do-ma-in.com
a@p.com
-------- invalid --------
somebody@example
a@p.com
.wooly@example.com
wo..oly@example.com
invalid:email@example.com
@somewhere.com
example.com
@@example.com
a space@example.com
something@ex..ample.com
a\\b@c
----- empty string ----
-------- space --------
someone@somewhere.com.
\\"\\"test\\blah\\"\\"@example.com
\\"testblah\\"@example.com
someone@somewhere.com@
someone@somewhere_com
someone@some:where.com
.
F/s/f/a@feo+re.com
some+long+email+address@some+host-weird-/looking.com
a @p.com
a\\u0020@p.com
a\\u0009@p.com
a\\u000B@p.com
a\\u000C@p.com
a\\u2003@p.com
a\\u3000@p.com
ddjk-s-jk@asl-.com
someone@do-.com
somebody@-p.com
somebody@-.com`;
// 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