Skip to content

Instantly share code, notes, and snippets.

@germanfrelo
Last active April 10, 2022 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save germanfrelo/799e616e672abe769ccfb69d42d93c05 to your computer and use it in GitHub Desktop.
Save germanfrelo/799e616e672abe769ccfb69d42d93c05 to your computer and use it in GitHub Desktop.
Best regular expression to validate email addresses

The best regular expression to validate email addresses

Reference: https://www.regular-expressions.info/email.html

I took the last regular expression example that appears at the end of the above web page and made some improvements:

  • I replaced every character (left single quotation mark, code U+2018) with the correct ` character (grave accent/backquote/backtick, code U+0060).

  • I replaced the last {1,63} with {2,63} so that the top-level domain must be at least 2 characters long instead of 1.

Regular expression

^(?=[a-z0-9@.!#$%&'*+/=?^_`{|}~-]{6,254}$)(?=[a-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:(?=[a-z0-9-]{1,63}\.)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?=[a-z0-9-]{2,63}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$

Regular expression for Java code

Every single backslash character (\) is replaced with two (\\) to turn the \ escape character itself into a string character.

^(?=[a-z0-9@.!#$%&'*+/=?^_`{|}~-]{6,254}$)(?=[a-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:(?=[a-z0-9-]{1,63}\\.)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?=[a-z0-9-]{2,63}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$

Tests

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment