RegexBuilder · regex answers
Regex for a domain name
/^(?!-)[a-z0-9-]{1,63}(?<!-)(\.(?!-)[a-z0-9-]{1,63}(?<!-))+$/iEach 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.
| Input | Result | Matched |
|---|---|---|
| example.com | matches | example.com |
| sub.example.co.uk | matches | sub.example.co.uk |
| x-1.example.org | matches | x-1.example.org |
| -example.com | no match | — |
| example-.com | no match | — |
| example | no match | — |
| exa mple.com | no 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 RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID