Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of 'example.com' |
[a-z0-9]+ |
Character class: one or more lowercase letters or digits | 'ex' in 'example' |
(?: |
Start of non-capturing group | Grouping for repetition |
- |
Literal hyphen character | Hyphen in 'sub-domain' |
[a-z0-9]+ |
Character class: one or more lowercase letters or digits | 'sub' in 'sub-domain' |
) |
End of non-capturing group | End of group |
* |
Quantifier: zero or more repetitions of the preceding group | Zero or more hyphen-separated segments |
\.? |
Escaped literal dot followed by optional quantifier (zero or one) | Dot in 'example.com' or absence in 'example' |
[a-z0-9-]* |
Character class: zero or more lowercase letters, digits, or hyphens | '-com' in 'example.com' |
[a-z0-9] |
Character class: exactly one lowercase letter or digit | 'm' in 'com' |
$ |
Anchor: asserts position at end of the string | End of 'example.com' |
Matches
exampleexample123sub-domainsub-domain.examplea-b-c123-abca.b-ca1-b2-c3
Does not match
Exampleexample..comexample-.com-example.comexample.com.example.com-example@comexample com
Common pitfalls
- Forgetting to escape the dot (\.) leading to incorrect matching of any character instead of a literal dot
- Assuming the pattern matches all valid domain names (e.g., it does not support uppercase letters or underscores)
- Overlooking the requirement for the string to end with an alphanumeric character, causing strings ending with hyphens to match incorrectly
Performance notes
The pattern is efficient due to the use of non-capturing groups and quantifiers. However, excessive use of quantifiers (e.g., nested *) could lead to catastrophic backtracking in pathological cases. Anchoring (^ and $) ensures the regex matches the entire string, which is optimal for validation tasks.