PatternRegex

Match a domain name

Pick domain names like sub.example.co.uk out of free text, allowing the hyphens real hostnames use while still requiring at least one dot.

Last updated

Patterngi
\b[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+\b
Open in Regex Tester & Builder

Matches

  • Visit example.com for details
  • sub-domain.example.co.uk works too
  • reach us at name@mail-server.io please

Doesn’t match

  • localhost has no dot at all
  • just_underscores_here nothing

Why it’s written this way

Each label is [a-z0-9]([a-z0-9-]*[a-z0-9])? — it must start and end with a letter or digit, with hyphens allowed only in the middle, which is exactly how DNS labels are defined (no leading or trailing hyphen). The label group then repeats after a literal dot one or more times via (\.[a-z0-9]...)+, so multi-level names like a.b.co.uk match in one pass.

The i flag makes the letter ranges case-insensitive without needing A-Z alongside a-z everywhere, since real-world hostnames show up in both cases in logs and copy-pasted text.

Edge cases to know

  • There is no TLD list, so made-up endings like .zzz match just as happily as .com — this checks shape, not registration.
  • Because it is unanchored, it matches the domain portion inside an email address too — reach@example.com will highlight example.com, which is usually what you want but is worth knowing.
  • It does not handle internationalized domain names (IDN) written as raw Unicode — only ASCII/punycode labels.

Related in Patterns