Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts the position at the start of the string | Start of '123-456-7890' |
\d |
Character class: matches any digit (0-9) | Digit '3' in '123' |
{3} |
Quantifier: specifies exactly 3 occurrences of the preceding token | Three digits '123' |
- |
Literal character: matches a hyphen | Hyphen '-' in '123-' |
\d |
Character class: matches any digit (0-9) | Digit '4' in '456' |
{3} |
Quantifier: specifies exactly 3 occurrences of the preceding token | Three digits '456' |
- |
Literal character: matches a hyphen | Hyphen '-' in '456-' |
\d |
Character class: matches any digit (0-9) | Digit '7' in '7890' |
{4} |
Quantifier: specifies exactly 4 occurrences of the preceding token | Four digits '7890' |
$ |
Anchor: asserts the position at the end of the string | End of '123-456-7890' |
Matches
123-456-7890000-000-0000987-654-3210
Does not match
1234567890123-456-789123-45-6789123-456-78901abc-def-ghij123 456 7890123-456-789a
Common pitfalls
- Forgetting to escape the hyphens (they are literal characters here).
- Assuming this matches international phone numbers or other formats.
- Not anchoring the pattern, which could lead to partial matches in longer strings.
- Confusing \d with \w or other character classes.
Performance notes
This pattern is efficient with no risk of catastrophic backtracking due to fixed quantifiers and no alternations or backreferences. Anchors ensure the entire string is validated, preventing partial matches.