Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts the position at the start of the string | Start of '123-45-6789' |
(?: |
Non-capturing group start | Starts grouping for the SSN pattern |
\d |
Digit character class (matches any digit 0-9) | Digit '1' in '123' |
{3} |
Quantifier: exactly 3 occurrences of the preceding token | Matches '123' in '123-45-6789' |
-? |
Optional hyphen (matches 0 or 1 hyphen) | Hyphen '-' in '123-45-6789' |
\d |
Digit character class (matches any digit 0-9) | Digit '4' in '45' |
{2} |
Quantifier: exactly 2 occurrences of the preceding token | Matches '45' in '123-45-6789' |
-? |
Optional hyphen (matches 0 or 1 hyphen) | Hyphen '-' in '45-6789' |
\d |
Digit character class (matches any digit 0-9) | Digit '6' in '6789' |
{4} |
Quantifier: exactly 4 occurrences of the preceding token | Matches '6789' in '123-45-6789' |
) |
Non-capturing group end | Ends grouping for the SSN pattern |
$ |
Anchor: asserts the position at the end of the string | End of '123-45-6789' |
Matches
123456789123-45-6789000123456999-88-7777
Does not match
12-345-67891234-56-78912345678123-45-6781234567890abc-def-ghij123--45-6789123-45--6789
Common pitfalls
- Assuming the pattern validates SSN validity (e.g., does not check for invalid SSN ranges like 000, 666, or 900-999 in the first group).
- Not accounting for leading/trailing whitespace (use trim() in JavaScript before matching).
- Misunderstanding that the hyphens are optional but must not appear in invalid positions (e.g., '123--45-6789' fails).
- Confusing this pattern with stricter SSN validation rules (e.g., some systems require hyphens in specific positions).
Performance notes
The pattern is efficient with no catastrophic backtracking risk due to fixed quantifiers and no nested quantifiers. Anchors (^ and $) ensure the entire string is matched, preventing partial matches.