Regex to Match Subdomains

Match and validate fully qualified domain names with subdomains. Captures each label in the domain hierarchy following DNS naming rules. Free regex tester.

Regular Expression

/^(?:([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)\.)+[a-zA-Z]{2,}$/

Token Breakdown

TokenDescription
^Anchors at the start of the string (or line in multiline mode)
(?:Start of non-capturing group
(Start of capturing group
[a-zA-Z0-9]Character class — matches any one of: a-zA-Z0-9
(?:Start of non-capturing group
[a-zA-Z0-9-]Character class — matches any one of: a-zA-Z0-9-
{0,61}Matches between 0 and 61 times
[a-zA-Z0-9]Character class — matches any one of: a-zA-Z0-9
)End of group
?Makes the preceding element optional (zero or one times)
)End of group
\.Matches a literal dot
)End of group
+Matches the preceding element one or more times (greedy)
[a-zA-Z]Character class — matches any one of: a-zA-Z
{2,}Matches 2 or more times
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex validates fully qualified domain names including subdomains according to DNS naming rules. Here is the token-by-token breakdown:

^ — Anchors the match at the start of the string.

(?: — Opens a non-capturing group for repeating domain labels.

(a-zA-Z0-9?) — Capturing group 1 matches a single DNS label. It starts with an alphanumeric character, optionally followed by up to 61 alphanumeric characters or hyphens and a final alphanumeric character. This enforces the DNS rules: labels cannot start or end with hyphens and can be at most 63 characters long.

. — Matches the literal dot separating domain labels.

)+ — The domain label group repeats one or more times, matching all labels including the subdomain portions and the second-level domain.

[a-zA-Z]{2,} — Matches the top-level domain (TLD), requiring at least two letters. This covers TLDs like com, org, net, io, and longer ones like technology or museum.

$ — Anchors the match at the end of the string.

No flags are used since case insensitivity is already handled by including both letter ranges in the character classes. This pattern validates domain names like www.example.com, api.staging.myapp.io, and mail.sub.domain.org. It enforces DNS label length limits and character restrictions.

This pattern is useful for domain validation in web applications, DNS configuration tools, and network security filtering.

Example Test Strings

InputExpected
www.example.comMatch
api.staging.myapp.ioMatch
exampleNo Match
-invalid.comNo Match
sub.domain.co.ukMatch

Try It — Interactive Tester

//
gimsuy
No matches found.
Pattern: 68 charsFlags: noneMatches: 0

Ctrl+Shift+C to copy regex

Customize this pattern →