Regex for Validating a Domain Name

Matches a domain made of one or more labels separated by dots, ending in a TLD.

Published October 12, 2026

This regex matches domain names with labels separated by dots and a TLD of at least two letters.

How the pattern works

Breaking the pattern down: [A-Za-z0-9-]{0,61} = label up to 63 characters; \. = dot; [A-Za-z]{2,} = TLD.

Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.

Pattern tests

/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$/
✓ 'example.com'
✓ 'sub.example.co.uk'
✗ '-bad.com'
✗ 'example'

Practical examples

The pattern

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

Test it

const re = /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$/
re.test('example.com')   // true
re.test('sub.example.co.uk')   // true
re.test('-bad.com')   // false
re.test('example')   // false

In Python

import re
re.search(r'^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$', text)

Common mistakes

  • Internationalised domains (punycode).
  • Hyphens at label edges.
  • Total length limit of 253.

Key takeaways

  • Anchors (^ and $) make the whole string match instead of a part of it.
  • Regex checks format only; verify data separately when it matters.
  • Test with valid and invalid samples.

FAQ

IDNs?

Convert to punycode first.

Where can I test this pattern?

Use the Regex Tester on this site, or regex101.com.

More General articles