Qaynaq LABS · TOOLS

REGEX · JAVASCRIPT

Regex explained

^\d{3}-\d{3}-\d{4}$

Matches a string representing a US phone number in the format XXX-XXX-XXXX, where X is a digit. The entire string must conform to this format from start to end.

Token-by-token breakdown

TokenMeaningExample
^ 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-7890
  • 000-000-0000
  • 987-654-3210

Does not match

  • 1234567890
  • 123-456-789
  • 123-45-6789
  • 123-456-78901
  • abc-def-ghij
  • 123 456 7890
  • 123-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.

About regular expressions

Regular expressions are tiny programs that match patterns in text. They're powerful and notoriously cryptic — most engineers can write them but few can read them confidently. Qaynaq Labs' regex explainer breaks any pattern into its constituent tokens, shows what each one does, and runs through both matching and non-matching examples so you can verify the logic.

Different regex flavors (JavaScript, PCRE, Python, Go) have subtle differences in syntax and supported features. Pick your flavor in the input — the explainer accounts for it.

Frequently asked

Does this pattern match international phone numbers?

No, this pattern is strictly for US-style phone numbers in the format XXX-XXX-XXXX.

Can I use this to validate phone numbers in user input?

Yes, but ensure the input is trimmed and normalized first, as this pattern does not account for leading/trailing whitespace or other formats.

What if I want to match optional parentheses around the area code?

You would need to modify the pattern, e.g., ^\(?\d{3}\)?-\d{3}-\d{4}$ for optional parentheses around the first 3 digits.