Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of 'example.com' |
[a-zA-Z0-9\-\.]+ |
Character class matching one or more alphanumeric characters, hyphens, or dots | Matches 'example', 'sub-domain', 'test.' |
+ |
Quantifier: one or more of the preceding token | Required for the first part of the domain |
\. |
Escaped literal dot character (matches a single '.') | The dot before the TLD in 'example.com' |
[a-zA-Z]{2,} |
Character class matching 2 or more alphabetic characters | Matches 'com', 'org', 'io' |
$ |
Anchor: asserts position at end of the string | End of 'example.com' |
Matches
example.comsub.domain.cotest-domain.orga.b.c.d123.456.xyzmy-site.net
Does not match
example..comexample.cexample.com..example.comexample@comexample comexample.c0mexample.com-
Common pitfalls
- Fails to match domains with underscores (e.g., 'example_domain.com')
- Does not validate internationalized domain names (IDNs)
- Allows consecutive dots (e.g., 'ex..ample.com') which are invalid in real domains
- Does not enforce TLD length limits (e.g., 'example.technology' is valid but long)
- Hyphens at start/end of labels are allowed but may be invalid in practice (e.g., '-example.com')
- Escaping the dot is correct here, but forgetting to escape it would make it a wildcard
Performance notes
The pattern is efficient with no catastrophic backtracking risk. The anchors (^ and $) ensure the entire string is matched, preventing partial matches. The character class [a-zA-Z0-9\-\.] is optimized for ASCII and does not require alternation.