Skip to content

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.

Pattern flags: i
^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$
Test this pattern in the Regex Tester →

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

Match
example.com
Matches: example.com
Match
sub.domain.co.uk
Matches: sub.domain.co.uk
No Match
-invalid.com

Common Uses

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.

Related Patterns

URL

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]...

Email Address

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA...

IPv4 Address

^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3...

Related Reading

Regex Cheat Sheet with Examples for Developers → URL Encoding Special Characters →