Quantcast
Channel: How can I validate an email address using a regular expression? - Stack Overflow
Viewing all articles
Browse latest Browse all 89

Answer by Tim Wißmann for How can I validate an email address using a regular expression?

$
0
0

For my purpose, I needed a way to also extract a display name if provided.
Thanks to the other answers and the regex provided on https://emailregex.com/ I came up with the following solution:

/^(?:([^<]*?)\s*<)?((?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\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-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]))>?$/gi

This matches Display name (=group 1)+email address (=group 2).

Examples of matches:

john.doe@example.comjohn.o'doe@example.comJohn <john@doe.com><john@doe.com>This is <john@127.0.0.1>

Tested with https://regex101.com/

Of course, as also mentioned in other answers, additional validation of the length of display name and email address is required (shouldn't exceed 320 UTF-8 bytes).


Viewing all articles
Browse latest Browse all 89

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>