Regex for Domain Name
This regex matches valid domain names with one or more subdomains and a top-level domain (TLD) of at least two characters. Each label (part between dots) can be up to 63 characters, must start and end with an alphanumeric character, and can contain hyphens in the middle. This follows the DNS naming rules defined in RFC 1035.
^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$ What is the regex pattern for Domain Name?
The regex pattern for Domain Name is ^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$ with the i flag. This regex matches valid domain names with one or more subdomains and a top-level domain (TLD) of at least two characters. Each label (part between dots) can be up to 63 characters, must start and end with an alphanumeric character, and can contain hyphens in the middle. This follows the DNS naming rules defined in RFC 1035. This pattern is commonly used for domain validation and dns configuration.
Test Examples
example.com example.com sub.domain.co.uk sub.domain.co.uk -invalid.com Common Uses
- ✓ Domain validation
- ✓ DNS configuration
- ✓ Email domain extraction
- ✓ SSL certificate validation
Variations
With optional www
^(?:www\.)?(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$ Optionally matches www prefix
Specific TLDs
^(?:[a-zA-Z0-9-]+\.)+(?:com|org|net|io|dev)$ Only matches specific top-level domains
With port
^(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(?::\d{1,5})?$ Allows optional port number
Frequently Asked Questions
What makes a domain name valid?
Each label must be 1-63 characters of letters, digits, and hyphens (no leading or trailing hyphens). The full domain cannot exceed 253 characters. The TLD must be at least two characters.
Does this match internationalized domain names (IDNs)?
No, this pattern only matches ASCII domain names. Internationalized domain names use Punycode encoding (xn-- prefix) for the ASCII-compatible form, which this pattern does match.
Why can labels not start or end with hyphens?
This is a DNS rule from RFC 1035. Labels starting with hyphens could be confused with command-line flags, and the restriction has been maintained for backward compatibility and readability.