Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts the position at the start of the string | Start of '123-45-6789' |
\d |
Character class: matches any digit (0-9) | Digit '3' in '123-45-6789' |
{3} |
Quantifier: specifies exactly 3 occurrences of the preceding token | Three digits '123' in '123-45-6789' |
- |
Literal hyphen character: matches a single hyphen | Hyphen '-' in '123-45-6789' |
\d |
Character class: matches any digit (0-9) | Digit '4' in '123-45-6789' |
{2} |
Quantifier: specifies exactly 2 occurrences of the preceding token | Two digits '45' in '123-45-6789' |
- |
Literal hyphen character: matches a single hyphen | Hyphen '-' in '123-45-6789' |
\d |
Character class: matches any digit (0-9) | Digit '6' in '123-45-6789' |
{4} |
Quantifier: specifies exactly 4 occurrences of the preceding token | Four digits '6789' in '123-45-6789' |
$ |
Anchor: asserts the position at the end of the string | End of '123-45-6789' |
Matches
123-45-6789000-00-0000999-99-9999
Does not match
12345678912-345-6789123-456-789123-45-678123-45-67890abc-def-ghij123 45 6789123-45-678A
Common pitfalls
- Assuming the pattern validates real SSNs (it only checks format, not validity).
- Forgetting to escape the hyphens (they are literal characters).
- Not anchoring the pattern (^ and $) may lead to partial matches in longer strings.
- Confusing \d with [0-9] (both work in JavaScript, but \d is more readable).
Performance notes
The pattern is linear in complexity (O(n)) and has no risk of catastrophic backtracking due to fixed quantifiers and no alternations or nested quantifiers. Anchoring ensures the entire string is matched, preventing partial matches.