I am trying to find the perfect regex that will help me extract the domain name of an email. (ex: [email protected]
should return domain.com
)
A lot of issue on SO address this problem but none of them treat it perfectly.
Here are the special edge cases that I want to tackle:
- I don't want to keep subdomains. (ex:
[email protected]
should returndomain.com
) - Some domain extensions have two dots. (ex:
[email protected]
should returndomain.co.uk
) - It is possible to include an at (
@
) in your domain name (although most registrar do not allow it). (ex:hello@[email protected]
should return[email protected]
)
I have tried the following regex but they don't tackle all the edge cases:
/(?<=@)\S+\.\S+$/
=> Does not handle case 1/[^.@]*?\.\w{2,}$|[^.@]*?\.com?\.\w{2}$/
=> Does not handle case 3