I have this regular expression for valid email addresses which works well: ^(?=[\w\s])\s*[- .'\w] @[-.\w] \.[-.\w]{2,}\s*$
However, users are sometimes entering an address like "[email protected]". I could exclude "co" from my regex, but I still want to allow "[email protected]", see here.
I looked at this post but I don't know how to include that in the part [-.\w]{2,} of my current expression.
How can I alter my regular expression to disallow ".co" at the end of an email address?
CodePudding user response:
You could write the pattern without the lookahead at the start as:
^\s*[- .'\w] @\w (?:[-.]\w )*\.(?!co\s*$)[a-z]{2,}\s*$
Note that [- .'\w] and \w limits the range of valid email addresses.
The pattern matches:
^Start of string\s*[- .'\w] @Match optional whitespace chars and repeat any listed chars in the character class until matching @\w (?:[-.]\w )*After the @ start with matching 1 word chars and optionally repeat either.or-and 1 word chars\.(?!co\s*$)Match a dot and use a negative lookahead asserting notcoand optional whitespace chars until the end of strinng[a-z]{2,}\s*Match 2 or more chars a-z and optional whitespace chars$End of string
See a Regex demo
If you don't want to allow matching leading whitespace chars, you can omit \s* from the start and the end of the pattern.
