RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex for a domain name

/^(?!-)[a-z0-9-]{1,63}(?<!-)(\.(?!-)[a-z0-9-]{1,63}(?<!-))+$/i

Each label is 1-63 characters of letters, digits and hyphens, and may not begin or end with a hyphen — which is what the lookahead and lookbehind enforce without consuming anything. This lookbehind is fixed-width, the widely supported kind: Python's standard re handles it, as do PCRE2 and .NET. JavaScript gained lookbehind in Node 8.3 and in Safari only in 16.4, so check your oldest runtime rather than assuming.

What each part does

(?!-)the label does not start with a hyphen
[a-z0-9-]{1,63}the label body, at most 63 characters
(?<!-)and it does not end with one
(\. … )+at least one more dot-separated label

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
example.commatchesexample.com
sub.example.co.ukmatchessub.example.co.uk
x-1.example.orgmatchesx-1.example.org
-example.comno match
example-.comno match
exampleno match
exa mple.comno match

The mistake to avoid

Allowing underscores because hostnames in some internal systems use them. They are legal in DNS records — _dmarc and _domainkey are everywhere — but not in the preferred hostname syntax of RFC 1035. Browsers do not refuse them: underscore is not a forbidden host character in the WHATWG URL Standard, so https://my_host.example.com parses. What breaks is stricter software downstream: certificate authorities will not issue for such a name, and some resolvers and load balancers reject it.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers