Regex to Match a Domain Name
Copy the pattern, paste your text below, and find every domain name it contains. Below the tester: how each label is bounded and why this is not a full hostname validator.
What this pattern matches
This expression matches a bare domain name — one or more labels joined by dots and ending in a letters-only top-level domain, such as example.com or sub.domain.co.uk. Unlike a URL pattern, it does not require http:// or a path.
How it works, part by part
[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])? — one label: it starts and ends with a letter or digit and may contain hyphens, up to 63 characters.
(?:…\.)+ — one or more labels each followed by a dot.
[a-zA-Z]{2,} — the top-level domain, at least two letters.
What it does not do
It does not check that the TLD actually exists, and it will match the host part of an email or URL if one is present. For strict validation against the current TLD list you need a lookup, not a regex. Use this to extract likely domains from free text.
Use it in your code
import re
text = "Visit example.com or sub.domain.co.uk. Not a domain: just-text, foo. Email host: gmail.com."
pattern = r'''\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\b'''
for m in re.finditer(pattern, text):
print(m.group())
const text = "Visit example.com or sub.domain.co.uk. Not a domain: just-text, foo. Email host: gmail.com.";
const re = new RegExp(String.raw`\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\b`, "g");
console.log(text.match(re));
FAQ
Does it match internationalised domains?
Only in their punycode form (xn--…). Unicode domains need to be converted to punycode before matching.
Will it match the domain inside an email address?
Yes. It matches gmail.com in name@gmail.com because that host is a valid domain. Split on @ first if you want only the standalone domains.
Does it verify the TLD is real?
No. It only requires two or more letters. Check against the IANA TLD list if you need certainty.