I am trying to find the perfect regex that will help me extract the domain name of an email. (ex: hello@domain.com
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:
hello@sub.domain.com
should returndomain.com
) - Some domain extensions have two dots. (ex:
hello@domain.co.uk
should returndomain.co.uk
) - It is possible to include an at (
@
) in your domain name (although most registrar do not allow it). (ex:hello@dom@in.com
should returndom@in.com
)
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