Skip to content

Find everything that’s not an email address using only regex

I need to find everything in a string that is not an e-mail address.

Here is my version of how to find an e-mail address.

^[a-zA-Z0-9_.-][email protected][a-zA-Z0-9][a-zA-Z0-9-.]+.([a-zA-Z]{2,6})$

I want to modify this regex to find the inverse–everything other than the e-mail address in any string.


###Example 1: asdasd

###Example 2: [email protected] sda


Note: I want to get status == true in the following line:

var status = myString.match(pattern matches everything that is not an email address);

###I can only change the pattern, nothing else!

Answer

The official standard is known as RFC 2822. Regex pattern for email address is then:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|\[x01-x09x0bx0cx0e-x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[x01-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|\[x01-x09x0bx0cx0e-x7f])+)])

More practical implementation of RFC 2822 (if we omit the syntax using double quotes and square brackets), which will still match 99.99% of all email addresses in actual use today, is:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

To get list of non-matching “words” from myString use JavaScript code:

var status = myString.match(/(?:s|^)(?![a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)S+b(?=s|$)/ig);

Check this demo.