Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of string |
(?: |
Start of a non-capturing group (for optional country code +1 with optional prefix '+' and optional separator) | Optional country code part |
\+? |
Optional literal '+' character (0 or 1 times) | + or nothing |
1 |
Literal digit '1' (country code for North America) | 1 |
[-. ]? |
Optional separator: one of '-', '.', or space (0 or 1 times) | -, ., space, or nothing |
)? |
End of non-capturing group, makes the entire group optional (0 or 1 times) | Optional country code block |
\(? |
Optional literal '(' character (0 or 1 times) | ( |
([0-9]{3}) |
Capturing group: exactly 3 digits (area code) | 123 |
\)? |
Optional literal ')' character (0 or 1 times) | ) |
[-. ]? |
Optional separator: one of '-', '.', or space (0 or 1 times) | -, ., space, or nothing |
([0-9]{3}) |
Capturing group: exactly 3 digits (exchange code) | 456 |
[-. ]? |
Optional separator: one of '-', '.', or space (0 or 1 times) | -, ., space, or nothing |
([0-9]{4}) |
Capturing group: exactly 4 digits (subscriber number) | 7890 |
$ |
Anchor: asserts position at end of the string | End of string |
Matches
1234567890+1 123 456 7890(123)4567890123.456.78901-123-456-7890+1(123)456-789012345678901 123 456 7890
Does not match
12345123456789123-456-789123.456.78912345678901abc1234567+44 123 456 7890123)456-7890
Common pitfalls
- Fails to match numbers with more than 10 digits (e.g., extensions).
- Does not validate area codes (e.g., 000, 111) or exchange codes (e.g., 000).
- May incorrectly match invalid separators if not careful (e.g., '123_456_7890').
- Overly permissive with optional separators, allowing ambiguous formats like '1234567890' or '123.4567890'.
Performance notes
Low risk of catastrophic backtracking due to simple quantifiers and limited alternation. Anchors (^ and $) ensure full-string matching, preventing partial matches. Non-capturing groups improve efficiency.