Advertisement

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

Test it: match & no-match examples

Every row is loaded straight into the tester — click Try to see the match live:

InputResultWhy
example.comMatchbare domainTry →
www.example.comMatchwith wwwTry →
a.b.example.comMatchmulti-level subdomainTry →
-example.comNo matchleading hyphen rejectedTry →
exampleNo matchmissing TLDTry →
example.123No matchnumeric TLD rejectedTry →

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.
Open the regex tester →

FAQ

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.