176

I need to validate a domain name:

google.com

stackoverflow.com

So a domain in its rawest form - not even a subdomain like www.

  1. Characters should only be a-z | A-Z | 0-9 and period(.) and dash(-)
  2. The domain name part should not start or end with dash (-) (e.g. -google-.com)
  3. The domain name part should be between 1 and 63 characters long
  4. The extension (TLD) can be anything under #1 rules for now, I may validate them against a list later, it should be 1 or more characters though

Edit: TLD is apparently 2-6 chars as it stands

no. 4 revised: TLD should actually be labelled "subdomain" as it should include things like .co.uk -- I would imagine the only validation possible (apart from checking against a list) would be 'after the first dot there should be one or more characters under rules #1

Thanks very much, believe me I did try!

10
  • 1
    May be not helpful at all. When it comes to google.co.uk, and some Japanese domains, I'm sure you will have to think twice before using regex for that. My personal thought is that regex is not enough to validate a domain to a real-life domain. FYI, here is an almost complete list of tlds and country code second level domains list: static.ayesh.me/misc/SO/tlds.txt
    – AKS
    May 15, 2012 at 14:42
  • 2
    See my answer to the related question about hostname validation.
    – SAM
    Sep 7, 2013 at 14:41
  • 2
    Often forgotten: For full qualified domain names you should match a period after the tld.
    – schmijos
    Nov 13, 2013 at 13:45
  • 1
    it's been 4 years, now the count is up to 89,000
    – mydoglixu
    Jan 8, 2016 at 15:49
  • 2
    Some of these answers are pretty good, but there's also another good answer on this other question that's worth a look. Jan 25, 2016 at 1:45

22 Answers 22

140

I know that this is a bit of an old post, but all of the regular expressions here are missing one very important component: the support for IDN domain names.

IDN domain names start with xn--. They enable extended UTF-8 characters in domain names. For example, did you know "♡.com" is a valid domain name? Yeah, "love heart dot com"! To validate the domain name, you need to let http://xn--c6h.com/ pass the validation.

Note, to use this regex, you will need to convert the domain to lower case, and also use an IDN library to ensure you encode domain names to ACE (also known as "ASCII Compatible Encoding"). One good library is GNU-Libidn.

idn(1) is the command line interface to the internationalized domain name library. The following example converts the host name in UTF-8 into ACE encoding. The resulting URL https://nic.xn--flw351e/ can then be used as ACE-encoded equivalent of https://nic.谷歌/.

  $ idn --quiet -a nic.谷歌
  nic.xn--flw351e

This magic regular expression should cover most domains (although, I am sure there are many valid edge cases that I have missed):

^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\.(xn--)?([a-z0-9\-]{1,61}|[a-z0-9-]{1,30}\.[a-z]{2,})$

When choosing a domain validation regex, you should see if the domain matches the following:

  1. xn--stackoverflow.com
  2. stackoverflow.xn--com
  3. stackoverflow.co.uk

If these three domains do not pass, your regular expression may be not allowing legitimate domains!

Check out The Internationalized Domain Names Support page from Oracle's International Language Environment Guide for more information.

Feel free to try out the regex here: http://www.regexr.com/3abjr

ICANN keeps a list of tlds that have been delegated which can be used to see some examples of IDN domains.


Edit:

 ^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?([a-z0-9][a-z0-9\-]{0,60}|[a-z0-9-]{1,30}\.[a-z]{2,})$

This regular expression will stop domains that have '-' at the end of a hostname as being marked as being valid. Additionally, it allows unlimited subdomains.

25
  • 1
    Note that this will only support max one subdomain, anything more than that will result in false. It's not something that you're libel to run into unless using it for internal sites, etc... A quick attempt to allow it to support more subdomains: /^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,}\.?((xn--)?([a-z0-9\-.]{1,61}|[a-z0-9-]{1,30})\.?[a-z]{2,})$/i
    – stakolee
    Aug 25, 2016 at 19:01
  • 1
    But lonely tld's are not working :( For example to. ( to. ) is valid url with content.
    – iiic
    Sep 16, 2016 at 8:41
  • 5
    @timgws But any character or character class or group matches exactly one time even without {1,1}. It's like writing h{1,1}i{1,1} instead of hi - just makes reading harder. May 23, 2018 at 6:35
  • 2
    @FilipBartuzi this is mentioned: use an IDN library to ensure you encode domain names to ACE. They are not actually valid domain names (DNS only supports a subset of letters and numbers, ACE/IDN is what makes these work). Jun 19, 2018 at 3:22
  • 2
    @Sandra com.com is a valid (and registered!) domain. Thus any subdomain of it is also valid. This Q&A is about validating the syntax of a domain, not whether it is fit for a particular purpose, nor whether someone has entered the "right" domain.
    – Walf
    Jul 24, 2023 at 0:43
70

Well, it's pretty straightforward a little sneakier than it looks (see comments), given your specific requirements:

/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/

But note this will reject a lot of valid domains.

22
  • 15
    @infensus - While this regex is correct given your specs, your specs are wrong. g.co is a valid domain name but g is only one character.
    – sch
    Apr 24, 2012 at 22:23
  • 3
    This should match all cases I think: ^([a-z0-9])(([a-z0-9-]{1,61})?[a-z0-9]{1})?(\.[a-z0-9](([a-z0-9-]{1,61})?[a-z0-9]{1})?)?(\.[a-zA-Z]{2,4})+$ May 16, 2013 at 16:38
  • 2
    x.com would not pass here Nov 6, 2013 at 23:22
  • 5
    @Neil: You're right. The original question asked for 3-63 characters (see edit 3). It can be changed to support one-character domains fairly easily: /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.[a-zA-Z]{2,}$/. But this still rejects tons of valid stuff...
    – Cameron
    Nov 7, 2013 at 1:02
  • 2
    this doesn't even support .co.uk tld either. Mar 18, 2019 at 2:25
55

My RegEx is next:

^[a-zA-Z0-9][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]{0,1}\.([a-zA-Z]{1,6}|[a-zA-Z0-9-]{1,30}\.[a-zA-Z]{2,3})$

it's ok for i.oh1.me and for wow.british-library.uk

UPD

Here is updated rule

^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$

Regular expression visualization

https://www.debuggex.com/r/y4Xe_hDVO11bv1DV

now it check for - or _ in the start or end of domain label.

17
  • 9
    Looks pretty good, but the {2,6} criteria will need to be updated for the new TLD. Probably {2,}.
    – jwatts1980
    Mar 12, 2014 at 14:42
  • @jwatts1980 is there an examples of such zones? or you mean for possible future zones?
    – paka
    Mar 13, 2014 at 13:42
  • 1
    Here is an article discussing the upcoming changes with examples and links to related resources: zdnet.com/…
    – jwatts1980
    Mar 13, 2014 at 15:26
  • 1
    Why ([a-zA-Z]{1}[a-zA-Z]{1}) and not ([a-zA-Z]{2})?
    – Anton
    Dec 17, 2014 at 21:47
  • 4
    the last part with the two alternatives is also wrong: there exists ccTLDs (two letters) that accept IDNA sublabels. There also exists now TLDs labels already using IDNA labels. You should not special case the last label which is not different from others (and now has many extensions added with variable lengths, jsut like all other labels in subdomains. note the IDNA labels may also appear Punycoded (in which case there will be "--" a segment in the label, the only case where "--" is allowed in labels.. Finally the underscore is invalid everywhere in all labels.
    – verdy_p
    Dec 6, 2015 at 2:45
46

My bet:

^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$

Explained:

Domain name is built from segments. Here is one segment (except final):

[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?

It can have 1-63 characters, does not start or end with '-'.

Now append '.' to it and repeat at least one time:

(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+

Then attach final segment, which is 2-63 characters long:

[a-z0-9][a-z0-9-]{0,61}[a-z0-9]

Test it here: http://regexr.com/3au3g

12
  • 1
    All other answers didn't worked for me but this one did.
    – OncleDan
    Jan 16, 2018 at 15:47
  • 1
    @pubkey, you need to convert those domain names to punycode. Actual name for редбулл.москва is xn--90afc0aazy.xn--80adxhks And my regex does match it. Jun 16, 2020 at 17:19
  • 4
    This really is the best regex that doens't go off the rails. It handles single character labels, it can handle IDN domains (converted to punycode), and has no absurd length requirement on TLD. I think you would be hardpressed to find a domain which it does not match. The only thing it doens't enforce is the max length of a domain (253 characters) However a simple length check could easily be used with the regex.
    – Nicholi
    Aug 24, 2020 at 18:09
  • 1
    As as I know, I think domains shouldn't start with numbers nor end with them (per rfc1035 on page 8). Note however that I could be wrong on ending on a digit; that might be allowed, but I've never seen it. My modified version of this (simply removes 0-9 in the first and last sequences): ^(?:[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z]$ Jul 30, 2021 at 3:11
  • 1
    A fully-qualified domain name can end with a final dot. dns-sd.org/trailingdotsindomainnames.html Apr 5, 2022 at 11:59
21

This answer is for domain names (including service RRs), not host names (like an email hostname).

^(?=.{1,253}\.?$)(?:(?!-|[^.]+_)[A-Za-z0-9-_]{1,63}(?<!-)(?:\.|$)){2,}$

It is basically mkyong's answer and additionally:

  • Max length of 255 octets including length prefixes and null root.
  • Allow trailing '.' for explicit dns root.
  • Allow leading '_' for service domain RRs, (bugs: doesn't enforce 15 char max for _ labels, nor does it require at least one domain above service RRs)
  • Matches all possible TLDs.
  • Doesn't capture subdomain labels.

By Parts

Lookahead, limit max length between ^$ to 253 characters with optional trailing literal '.'

(?=.{1,253}\.?$)

Lookahead, next character is not a '-' and no '_' follows any characters before the next '.'. That is to say, enforce that the first character of a label isn't a '-' and only the first character may be a '_'.

(?!-|[^.]+_)

Between 1 and 63 of the allowed characters per label.

[A-Za-z0-9-_]{1,63}

Lookbehind, previous character not '-'. That is to say, enforce that the last character of a label isn't a '-'.

(?<!-)

Force a '.' at the end of every label except the last, where it is optional.

(?:\.|$)

Mostly combined from above, this requires at least two domain levels, which is not quite correct, but usually a reasonable assumption. Change from {2,} to + if you want to allow TLDs or unqualified relative subdomains through (eg, localhost, myrouter, to.)

(?:(?!-|[^.]+_)[A-Za-z0-9-_]{1,63}(?<!-)(?:\.|$)){2,}

Unit tests for this expression.

5
  • 2
    Thanks! This is the best regex here. Your thorough explanation and unit test are a bonus.
    – naudster
    Mar 27, 2017 at 2:59
  • What does "RR" mean?
    – wheeler
    Dec 4, 2017 at 15:27
  • Resource Record. Usually a text or informational field that tells you how to interact with a service. Dec 4, 2017 at 16:55
  • This regex is not correct. For example the domain redbull.移动 is valid but the regex will not match.
    – pubkey
    Jun 15, 2020 at 12:03
  • Convert to punycode first, then match. Length limits on the pre-punycode version are really hard to implement. Jun 15, 2020 at 12:06
17

Just a minor correction - the last part should be up to 6. Hence,

^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}$

The longest TLD is museum (6 chars) - http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains

7
  • 3
    Note: This will not pass the valid (yet rare) domain name www.my---domain.com
    – Chris Bier
    Sep 17, 2013 at 21:35
  • 18
    Doesn't cut it with new TLD e.g. .photography Mar 12, 2014 at 10:57
  • 2
    @SamFigueroa You'll just have to modify the length of it Jul 5, 2015 at 11:11
  • 3
    there shouldn't be a check for the TLD it's not different from the subdomains. And basing the regex on currently available tlds isn't future proof. Apr 4, 2016 at 14:49
  • 1
    Suggest last bit be {2,63}: see stackoverflow.com/questions/9238640/…
    – Eric Dobbs
    Jan 25, 2019 at 16:02
15

Accepted answer not working for me, try this :

^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,6}$

Visit this Unit Test Cases for validation.

9
  • 4
    no support for new longer TLD names like .audio, .photography, and most of these... data.iana.org/TLD/tlds-alpha-by-domain.txt Apr 15, 2015 at 15:35
  • @mrbinky3000 Just change the last {2,6} to something else and it'll work. Mine: ^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+(?!-)[a-zA-Z0-9-]{1,63}(?<!-)$
    – Mygod
    Jan 6, 2017 at 2:24
  • @Mygod your regex contains some zero width garbage past the last question mark, so anyone copying it will be unpleasantly surprised
    – MightyPork
    May 14, 2017 at 17:58
  • 1
    @MightyPork You're right! Sorry here's a (hopefully) clean version: ^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+(?!-)[a-zA-Z0-9-]{1,63}(?<!-)$
    – Mygod
    May 15, 2017 at 3:00
  • 1
    So I changed it to /^(?:(?!-)[a-z0-9-]{0,62}[a-z0-9]\.)+[a-z]{2,}$/i.Slightly less elegant, but does the job.
    – PhiLho
    Dec 6, 2018 at 10:28
12

As already pointed out it's not obvious to tell subdomains in the practical sense (e.g. .co.uk domains). We use this regex to validate domains which occur in the wild. It covers all practical use cases I know of. New ones are welcome. According to our guidelines it avoids non-capturing groups and greedy matching.

^(?!.*?_.*?)(?!(?:[\d\w]+?\.)?\-[\w\d\.\-]*?)(?![\w\d]+?\-\.(?:[\d\w\.\-]+?))(?=[\w\d])(?=[\w\d\.\-]*?\.+[\w\d\.\-]*?)(?![\w\d\.\-]{254})(?!(?:\.?[\w\d\-\.]*?[\w\d\-]{64,}\.)+?)[\w\d\.\-]+?(?<![\w\d\-\.]*?\.[\d]+?)(?<=[\w\d\-]{2,})(?<![\w\d\-]{25})$

Proof, explanation and examples: https://regex101.com/r/FLA9Bv/9 (Note: currently only works in Chrome because the regex uses lookbehinds which are only supported in ECMA2018)

There're two approaches to choose from when validating domains.

By-the-books FQDN matching (theoretical definition, rarely encountered in practice):

Practical / conservative FQDN matching (practical definition, expected and supported in practice):

  • by-the-books matching with the following exceptions/additions
  • valid characters: [a-zA-Z0-9.-]
  • labels cannot start or end with hyphens (as per RFC-952 and RFC-1123/2.1)
  • TLD min length is 2 character, max length is 24 character as per currently existing records
  • don't match trailing dot
4
  • It's wonderful, although it should not validate `a.b-.cc.
    – Ste
    Apr 15, 2021 at 17:39
  • You're right, thanks for pointing that out. Can't promise to look into it now but happy to take suggestions. Apr 15, 2021 at 20:11
  • This regex will make your app crash in safari
    – Filip
    Nov 21, 2021 at 20:36
  • Good job! I made a variant for coma separated domains: stackoverflow.com/questions/28057243/…
    – Gawrion
    Sep 29, 2022 at 14:05
9

Thank you for pointing right direction in domain name validation solutions in other answers. Domain names could be validated in various ways.

If you need to validate IDN domain in it's human readable form, regex \p{L} will help. This allows to match any character in any language.

Note that last part might contain hyphens too! As punycode encoded Chineese names might have unicode characters in tld.

I've came to solution which will match for example:

  • google.com
  • masełkowski.pl
  • maselkowski.pl
  • m.maselkowski.pl
  • www.masełkowski.pl.com
  • xn--masekowski-d0b.pl
  • 中国互联网络信息中心.中国
  • xn--fiqa61au8b7zsevnm8ak20mc4a87e.xn--fiqs8s

Regex is:

^[0-9\p{L}][0-9\p{L}-\.]{1,61}[0-9\p{L}]\.[0-9\p{L}][\p{L}-]*[0-9\p{L}]+$

Check and tune here

NOTE: This regexp is quite permissive, as is current domain names allowed character set.

UPDATE: Even more simplified, as a-aA-Z\p{L} is same as just \p{L}

NOTE2: The only problem is that it will match domains with double dots in it... , like masełk..owski.pl. If anyone know how to fix this please improve.

3
  • We can just use [:alpha:] and [:digit] instead of \p{L}. It works fine.
    – puchu
    Apr 26, 2018 at 21:38
  • You can't validate an IDN this way without first converting it to punycode. For example with your expr, 中国互联网络信息中心中国互联网络信息中心中国互联网络信.中国 checks as valid, but after IDN conversion, it's too many bytes per label. \p{L} matches symbols, not punycode bytes (which vary from symbol to symbol), so repeat count is unhelpful when trying to limit its post-conversion size. Nov 2, 2018 at 18:36
  • Good point, each part is limited to 64 bytes. However we can't check it with RegExp, so further validation steps are required using punycode decoder - which will fail with your example hostname. The chineese must be mad by this limitation.
    – PeterM
    Nov 2, 2018 at 18:52
9
^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,7}$

[domain - lower case letters and 0-9 only] [can have a hyphen] + [TLD - lower case only, must be beween 2 and 7 letters long]
http://rubular.com/ is brilliant for testing regular expressions!
Edit: Updated TLD maximum to 7 characters for '.rentals' as Dan Caddigan pointed out.

1
  • 3
    Why limit TLDs? Now .photography would be invalid. Just make it unlimited chars or something like that.
    – adriaan
    Aug 13, 2018 at 17:52
5

Not enough rep yet to comment. In response to paka's solution, I found I needed to adjust three items:

  • The dash and underscore were moved due to the dash being interpreted as a range (as in "0-9")
  • Added a full stop for domain names with many subdomains
  • Extended the potential length for the TLDs to 13

Before:

^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$

After:

^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][-_\.a-zA-Z0-9]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,13}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$
3

For new gTLDs

/^((?!-)[\p{L}\p{N}-]+(?<!-)\.)+[\p{L}\p{N}]{2,}$/iu
4
  • 3
    Please give us some more details what you answer make better than the others? What do you match more?Please edit your post directly to add the information.
    – Sven R.
    Mar 11, 2016 at 9:33
  • Like i wrote: new gTLDs. Domains with unicode chars and also unicode TLDs.
    – Ben Keil
    Jul 19, 2016 at 7:58
  • 1
    @BenKeil: What is this part about: (?<!-)
    – jor
    Jan 13, 2017 at 10:32
  • @jor that is negative look behind. Check this out shortcutfoo.com/app/dojos/regex/cheatsheet Mar 29, 2018 at 8:20
2
^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]+(\.[a-zA-Z]+)$
1
  • 5
    -1 for the addition of {2,4}. It's possible to have single character TLDs (however, there are not currently any in the root). What about .mobile? .associates? Both are valid TLDs, and would be rejected by this regex. data.iana.org/TLD/tlds-alpha-by-domain.txt Nov 18, 2014 at 5:52
2

^[a-zA-Z0-9][-a-zA-Z0-9]+[a-zA-Z0-9].[a-z]{2,3}(.[a-z]{2,3})?(.[a-z]{2,3})?$

Examples that work:

stack.com
sta-ck.com
sta---ck.com
9sta--ck.com
sta--ck9.com
stack99.com
99stack.com
sta99ck.com

It will also work for extensions

.com.uk
.co.in
.uk.edu.in

Examples that will not work:

-stack.com

it will work even with the longest domain extension ".versicherung"

0
2

Here is complete code with example:

<?php
function is_domain($url)
{
    $parse = parse_url($url);
    if (isset($parse['host'])) {
        $domain = $parse['host'];
    } else {
        $domain = $url;
    }

    return preg_match('/^(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$/', $domain);
}

echo is_domain('example.com'); //true
echo is_domain('https://example.com'); //true
echo is_domain('https://.example.com'); //false
echo is_domain('https://localhost'); //false
2
^((localhost)|((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,253})$

Thank you @mkyong for the basis for my answer. I've modified it to support longer acceptable labels.

Also, "localhost" is technically a valid domain name. I will modify this answer to accommodate internationalized domain names.

1

Quite simple, quite permissive. It will have false positives like -notvalid.at-all, but it won't have false negatives.

/^([0-9a-z-]+\.?)+$/i

It makes sure it has a sequence of letters numbers and dashes that could end with a dot, and following it, any number of those kind of sequences.

The things I like about this regexp: it's short (maybe the shortest here), easily understandable, and good enough for validating user input errors in the client side.

1
  • I like this @pykiss. Simplicity in Regexes is important for maintainability. I think you can simplify this further by using \w as any word character like [a-zA-Z0-9_], which will include underscores, which is good. So it can become simply: ^([\w-]+\.?)+$
    – stwr667
    Feb 20 at 8:05
0
/^((([a-zA-Z]{1,2})|([0-9]{1,2})|([a-zA-Z0-9]{1,2})|([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]))\.)+[a-zA-Z]{2,6}$/
  • ([a-zA-Z]{1,2}) -> for accepting only two characters.

  • ([0-9]{1,2})-> for accepting two numbers only

if anything exceeds beyond two ([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]) this regex will take care of that.

If we want to do the matching for at least one time + will be used.

0
  • ^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,}\.?((xn--)?([a-z0-9\-.]{1,61}|[a-z0-9-]{0,30})\.[a-z-1-9]{2,})$

will validate such domains as яндекс.рф after encoding.

https://regex101.com/r/Hf8wFM/1 - sandbox

1
  • It's really good solutions, but the only problem with that it's supports domain over 63 characters, despite {0,61}. You know why?
    – test
    Nov 14, 2022 at 14:38
0

The following regex extracts the sub, root and tld of a given domain:

^(?<domain>(?<domain_sub>(?:[^\/\"\]:\.\s\|\-][^\/\"\]:\.\s\|]*?\.)*?)(?<domain_root>[^\/\"\]:\s\.\|\n]+\.(?<domain_tld>(?:xn--)?[\w-]{2,7}(?:\.[a-zA-Z-]{2,3})*)))$

Tested for the following domains:

* stack.com
* sta-ck.com
* sta---ck.com
* 9sta--ck.com
* sta--ck9.com
* stack99.com
* 99stack.com
* sta99ck.com
* google.com.uk
* google.co.in

* google.com
* masełkowski.pl
* maselkowski.pl
* m.maselkowski.pl
* www.masełkowski.pl.com
* xn--masekowski-d0b.pl
* xn--fiqa61au8b7zsevnm8ak20mc4a87e.xn--fiqs8s

* xn--stackoverflow.com
* stackoverflow.xn--com
* stackoverflow.co.uk
0

I did the below to simple fetch the domain along with the protocol. Example: https://www.facebook.com/profile/user/ ftp://182.282.34.337/movies/M

use the below Regex pattern : [a-zA-Z0-9]+://.*?/

will get you the output : https://www.facebook.com/ ftp://192.282.34.337/

-1

For Javascript you can have a look into the validator library: https://www.npmjs.com/package/validator

Method: isFQDN(str [, options])

Not the answer you're looking for? Browse other questions tagged or ask your own question.