Advertisement

Pattern library / Extract & Replace

Regex to Extract the Domain from a URL

Log lines and analytics exports bury the hostname in the middle of full URLs (https://www.example.com:8443/path?x=1). A capture group after the scheme stops exactly at the first /, : or end-of-string — no URL parser needed for the common cases.

The pattern
^https?://([^/:?#]+)
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
https://www.example.com/path?q=1Matchcaptures www.example.comTry →
http://blog.site.co.uk:8080/xMatchport stops the matchTry →
https://example.comMatchno path — matches to endTry →
ftp://files.example.comNo matchscheme limited to http(s)Try →
//cdn.example.com/lib.jsNo matchprotocol-relative — see pitfallsTry →
https://user:pass@example.com/xMatchcaptures user:pass — strip creds (pitfalls)Try →

Where to use it

JavaScript

const m = 'https://www.example.com/x'.match(/^https?:\/\/([^/:?#]+)/);
const host = m && m[1].replace(/^www\./, '');  // 'example.com'

Python

import re
m = re.search(r'^https?://([^/:?#]+)', 'http://blog.site.co.uk/x')
host = m.group(1)  # 'blog.site.co.uk'

SQL / BigQuery

SELECT REGEXP_EXTRACT(url, r'^https?://([^/:?#]+)') AS host FROM events

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

How do I capture the domain but not subdomains?

You cannot reliably — blog.example.co.uk and example.co.uk are ambiguous to regex. Capture the full host, then use the public suffix list (or a small library) to reduce it.

How do I extract domain AND path separately?

Two groups: ^https?://([^/:?#]+)([^?#]*) — group 1 is the host, group 2 the path up to any query or fragment.

Does this work on BigQuery or GA4?

Yes — REGEXP_EXTRACT with this pattern returns the host directly; it is plain RE2 syntax.

URL Regex — Match http/https Links (Practical) · Remove Query Parameters with Regex (Replace Example) · UTM Parameter Regex — Match & Extract utm_* Tags

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.