Regex for domain name

Use /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$/ to check that a whole string is a valid for domain name. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$/
Open in Regex Tester
InputResult
example.com✓ Match
sub.example.co.uk✓ Match
my-site.dev✓ Match
-example.com✗ No match
example✗ No match
example-.com✗ No match
https://example.com✗ No match

How the pattern works

PartMeaning
[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?A label of 1–63 characters that doesn’t start or end with a hyphen
\.A dot after each label
(?:…)+One or more labels (subdomains)
[A-Za-z]{2,}$The top-level domain

Code examples

JavaScript

const re = /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}', value))

PHP

preg_match('/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$/', $value) === 1;

Notes and limitations

Internationalized domains must be converted to their punycode form (xn--…) first. Look up a domain’s records with the DNS Lookup.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for domain name?
/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: example.com, sub.example.co.uk, my-site.dev. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.