The Hostname Regex

Viewed 44287

I'm looking for the regex to validate hostnames. It must completely conform to the standard. Right now, I have

^[0-9a-z]([0-9a-z\-]{0,61}[0-9a-z])?(\.[0-9a-z](0-9a-z\-]{0,61}[0-9a-z])?)*$

but it allows successive hypens and hostnames longer than 255 characters. If the perfect regex is impossible, say so.

Edit/Clarification: a Google search didn't reveal that this is a solved (or proven unsolvable) problem. I want to to create the definitive regex so that nobody has to write his own ever. If dialects matter, I want a a version for each one in which this can be done.

7 Answers

I tried all answers with these examples below and unfortunately no one has passed the test.

ec2-11-111-222-333.cd-blahblah-1.compute.amazonaws.com
domaine.com
subdomain.domain.com
12533d5.dkkkd.com
2dotsextension.co
1dotextension.c
ekkej_dhh.com
12552.2225
112.25.25
12345.com
12345.123.com
domaine.123
whatever
9999-ee.99
email@domain.com
.jjdj.kkd
-subdomain.domain.com
@subdomain.domain.com
112.25.25

Here is a better solution.

^[A-Za-z0-9][A-Za-z0-9-.]*\.\D{2,4}$

Just please post any other not considered case if exists @ https://regex101.com/r/89zZkW/1

According to the relevant internet RFCs and assuming you have lookahead and lookbehind positive and negative assertions:

If you want to validate a local/leaf hostname for use in an internet hostname (e.g. - FQDN), then:

^(?!-)[-a-zA-Z0-9]{1,63}(?<!-)$

That ^^^ is also the general check that a label component inside an internet hostname is valid.

If you want to validate an internet hostname (e.g. - FQDN), then:

^(?=.{1,253}\.?$)(?:(?!-)[-a-zA-Z0-9]{1,63}(?<!-)\.)*(?!-)[-a-zA-Z0-9]{1,63}(?<!-)\.?$
Related