KingJulian KingJulian - 3 months ago 11
Javascript Question

RegEx match only final domain name from any email address

I want to match only parent domain name from an email address, which might or might not have a subdomain.

So far I have tried this:

new RegExp(/.+@(:?.+\..+)/);


The results:

Input: abc@subdomain.maindomain.com
Output: ["abc@subdomain.domain.com", "subdomain.maindomain.com"]

Input: abc@maindomain.com
Output: ["abc@maindomain.com", "maindomain.com"]


I am interested in the second match (the group).

My objective is that in both cases, I want the group to match and give me only
maindomain.com


Note: before the down vote, please note that neither have I been able to use existing answers, nor the question matches existing ones.

Answer

You can use this regex:

/@(?:[^.\s]+\.)*([^.\s]+\.[^.\s]+)$/gm

Use captured group #1 for your result.

  • It matches @ followed by 0 or more instance of non-DOT text and a DOT i.e. (?:[^.\s]+\.)*.
  • Using ([^.\s]+\.[^.\s]+)$ it is matching and capturing last 2 components separated by a DOT.

RegEx Demo