Pattern library / Network & URLs
Regex to Match Domain Names (with Subdomains)
Matches example.com, www.example.com, a.b.example.com. Does not validate TLD existence — use DNS lookup for that.
The pattern
^([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z]{2,}$
Load this pattern into the tester →
How the pattern works
[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?— label: starts/ends alphanumeric, hyphens allowed inside.\.— dot separator.[A-Za-z]{2,}— TLD of 2+ letters.- Regex validates shape; verify the domain actually exists via DNS.
Test it: match & no-match examples
Every row is loaded straight into the tester — click Try to see the match live:
| Input | Result | Why | |
|---|---|---|---|
example.com | Match | bare domain | Try → |
www.example.com | Match | with www | Try → |
a.b.example.com | Match | multi-level subdomain | Try → |
-example.com | No match | leading hyphen rejected | Try → |
example | No match | missing TLD | Try → |
example.123 | No match | numeric TLD rejected | Try → |
Where to use it
JavaScript
const re = /^([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z]{2,}$/;
re.test('www.example.com'); // true
Python
import re
re.match(r'^([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z]{2,}$', 'www.example.com')
Common mistakes
Test this pattern on your own data
Paste it into the free tester with your real strings — nothing leaves your browser.
FAQ
Related patterns
For GA4-specific patterns, see the GA4 regex cheat sheet, the page path regex guide, the event filter regex guide, the GA4 regex match types, the custom channel grouping guide and RE2 vs PCRE. Browse the full regex pattern library.