0

How can I check either string is full domain or subdomain using regex.

like

abc.com | Full domain
xyz.abc.com | Subdomain
test.co.uk | Full domain
text.test.co.uk/ | Subdomain
4
  • why do you want to use regex? Commented Jun 25, 2012 at 14:19
  • 1
    There are domains like xxx.com.hk, which to regex will look the same as xyz.abc.uk. Don't use REGEX! Commented Jun 25, 2012 at 14:20
  • possible duplicate of Regex to extract subdomain from URL? Commented Jun 25, 2012 at 14:21
  • then what you suggest how to achveive it? Commented Jun 25, 2012 at 14:21

2 Answers 2

2

Recursively do a DNS lookup, while removing one section from the left at a time

subdomain

xyz.abc.com //DNS check PASS
abc.com //DNS check PASS

domain

xxx.com.hk //DNS check PASS
com.hk //DNS check FAIL

If there no nameservers/DNS resolution fails for a different reason, the other way to confirm if it is a subdomain or not is to use IANA's TLD (Top-Level Domain) Registry Here.

(USE CAUTIOUSLY)

There are several cases like com.com, com.google.com, and several other URLs using TLDs in their name.

Sign up to request clarification or add additional context in comments.

8 Comments

+1 for DNS Solution. You can't say without a lookup what is or isn't a second level domain.
What if valid domain name has no name servers?
If a DNS check fails, there is only one other way. To check it against all the names in the IANA registry. Updating the answer.
But some tld(s) are actually indirect, such as us.com, de.com, etc (see centralnic.com/names/domains), and IANA does not recognize them. Very well know such tlds are co.uk, co.jp, or com.br.
In my UPDATE, if you see a no-match just once, it is a domain. And if you see a no-match more than once, it is a sub-domain.
|
0

With Regex if not possible to check is a domain or subdomain. The most browser use for this problem the project of Mozilla - PublicSuffix. It is a maintained list of TLD.

You can use the following nuget package. (Install-Package Nager.PublicSuffix) https://www.nuget.org/packages/Nager.PublicSuffix/

Example:

 var domainParser = new DomainParser();
 var data = await domainParser.LoadDataAsync();
 var tldRules = domainParser.ParseRules(data);
 domainParser.AddRules(tldRules);

 var domainName = domainParser.Get("sub.test.co.uk");
 //domainName.Domain = "test";
 //domainName.Hostname = "sub.test.co.uk";
 //domainName.RegistrableDomain = "test.co.uk";
 //domainName.SubDomain = "sub";
 //domainName.TLD = "co.uk";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.