DevTools Hub

Search tools

Search for a developer tool

Regex for Domains

Part of the Regex Toolkit
Pattern
^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$

matches domain names only, not IP addresses or internationalized (punycode) TLDs

Explanation

A domain name is one or more labels separated by dots, and each label follows the same rule: 1 to 63 characters, letters/digits/hyphens only, and it can't start or end with a hyphen — -example.com and example-.com are both invalid, even though a hyphen in the middle (my-site.com) is completely normal. The final label — the TLD — is required and, per this pattern, letters only, at least 2 characters, since real top-level domains are always alphabetic.

This intentionally does not match an IP address like 192.168.1.1 — that's a different thing with its own shape, covered by the "IPv4" preset in Regex Builder. If your input could legitimately be either a domain or an IP address (a server hostname field, for instance), you need both patterns, not one that tries to cover both.

Two real gaps worth knowing about, both cases of the pattern being too strict for names that are valid in practice: an internationalized domain in its ASCII/punycode form (xn--fiqs8s, the wire-format encoding for a TLD like .中国) contains digits and hyphens, so it fails the letters-only TLD check here. And a DNS label that starts with an underscore — _dmarc.example.com, _acme-challenge.example.com, common in TXT and SRV records for email authentication and certificate validation — is outside strict hostname syntax and gets rejected too, even though real DNS servers accept and use these constantly.

Valid examples

  • example.com

    A standard two-part domain.

  • sub.example.co.uk

    A subdomain plus a multi-part TLD — any number of dot-separated labels before the final one is fine.

  • my-site.com

    A hyphen in the middle of a label is valid; only a leading or trailing hyphen isn't.

Invalid examples

  • -example.com

    A label can't start with a hyphen.

  • example..com

    A double dot creates an empty label, which isn't valid.

  • example.c

    A 1-character TLD — real top-level domains are at least 2 characters.

Try it now