The Pattern
``regex
^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$
`
Flags: gm — multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
example.com | ✅ matches |
sub.domain.co.uk | ✅ matches |
-bad.com | ❌ rejected |
localhost | ❌ rejected |
Labels, Not Domains
The pattern validates one label at a time and repeats it. Each label may be 1–63 characters,
must start and end with an alphanumeric, and may contain hyphens in between — which is
exactly the DNS rule, and why -bad.com is rejected.
The final group [a-zA-Z]{2,} requires a TLD of at least two letters, which is why
localhost does not match. That is correct for a public domain and wrong for a hostname,
so pick the pattern that matches what you are validating.
The Limits of This Pattern
Internationalised domains are the big gap: münchen.de is a real domain that this pattern
rejects, because DNS stores it in Punycode as xn--mnchen-3ya.de. Convert to ASCII with an
IDNA library before validating.
The total length limit of 253 characters is also unenforced here, and no pattern can tell you
whether a domain resolves, is registered, or belongs to whoever claims it.
Testing Before Shipping
A regex that has only been tried against inputs you expect to match is untested. Every
pattern needs three kinds of case:
1. Valid inputs that should match, including the awkward-but-legal ones.
2. Invalid inputs that should not, especially near-misses that differ by one character.
3. Adversarial inputs — very long strings, unusual Unicode, and nesting that could
trigger catastrophic backtracking.
Paste your own examples into the tester above and watch which lines highlight. A pattern
that matches everything you throw at it is usually too permissive rather than correct.
Catastrophic Backtracking
Nested quantifiers over overlapping character classes — (a+)+, (\w+\s?)* — can take
exponential time on a non-matching input. On a server that is a denial-of-service bug, not a
performance issue. If a pattern is applied to user input, bound the input length first and
prefer explicit alternation over nested repetition.
Anchors, Greediness and Backtracking
Three behaviours account for most regex surprises, and this pattern shows all three.
Anchors. ^ and $ pin the match to the start and end of the input. Without them,
\d{3} matches the 123 inside abc123def. With m in the flags — as here — they
pin to each *line* instead, which is what lets one pattern be tested against a list.
Greediness. .* takes as much as it can and gives back only when forced; .*? takes
as little as possible. On , the pattern <.*> matches the whole string and
<.*?> matches just .
Testing It Properly
`javascript
const pattern = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/gm;