Regex for Domain Name — Pattern Explained with Examples
DodaTech
Updated 2026-06-20
2 min read
In this tutorial, you'll learn about Regex for Domain Name. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Domain name validation is essential for URL processing, email validation, and network configuration. This pattern checks that a string follows DNS label conventions: alphanumeric characters and hyphens, no leading or trailing hyphens, and a valid top-level domain.
The Pattern
/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/
Pattern Breakdown
| Part | Meaning |
|---|---|
^ |
Start-of-string anchor |
(?: |
Non-capturing group for a single label plus dot |
[a-zA-Z0-9] |
Label must start with a letter or digit |
(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])? |
Middle chars: 0–61 alphanumeric or hyphens, ending with alphanumeric |
\. |
Literal dot separator |
)+ |
One or more label-dot groups (subdomains) |
[a-zA-Z]{2,} |
TLD: at least two alphabetic characters |
$ |
End-of-string anchor |
Matches
example.comsub.domain.commy-site.iogoogle.co.ukapi.v1.example.org
Does NOT Match
-example.comexample..com.comexample.c(too short TLD)exam ple.comhttp://example.com
Language Examples
JavaScript
const domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
console.log(domainRegex.test('example.com')); // true
console.log(domainRegex.test('-example.com')); // false
Python
import re
pattern = r'^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$'
print(bool(re.match(pattern, 'example.com'))) # True
print(bool(re.match(pattern, '-example.com'))) # False
Common Pitfalls
- TLD minimum length is 2, but many new gTLDs are longer (e.g.,
.international,.technology) — the{2,}quantifier handles this correctly - Internationalized domain names (IDN) use punycode (
xn--) prefixes which this ASCII-only pattern does not match - The full domain must be 253 characters or fewer, and each label maxes out at 63 characters — this pattern enforces label length but not total length
- Do not include protocol (
http://), port numbers, or path segments in domain validation — use a URL regex for those - Trailing dots (FQDN notation) are technically valid in DNS but rejected by this pattern
Real-World Use Cases
- Email validation — the domain portion after
@must be a valid domain name - Link sanitization — extract and verify domain names from user-submitted URLs
- DNS configuration tools — validate domain entries before making DNS API calls
FAQ
Related Patterns
Regex for Email Regex for URL
← Previous
Regex for Base64 — Pattern Explained with Examples
Next →
Regex for Alphanumeric — Pattern Explained with Examples
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro