Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of string |
(?: |
Start of a non-capturing group | Start of optional country code block |
\+ |
Matches a literal '+' character | + |
\d |
Matches a digit (0-9) | 1 |
{1,3} |
Quantifier: matches 1 to 3 of the preceding token (digits) | 12 or 123 |
[-.\s]? |
Character class followed by optional quantifier: matches a single character that is a hyphen, dot, or whitespace | - or . or space |
)? |
End of non-capturing group with optional quantifier (0 or 1) | Optional country code block |
\(? |
Escaped '(' followed by optional quantifier: matches an optional opening parenthesis | ( |
\d |
Matches a digit (0-9) | 3 |
{3} |
Quantifier: matches exactly 3 of the preceding token (digits) | 333 |
\)? |
Escaped ')' followed by optional quantifier: matches an optional closing parenthesis | ) |
[-.\s]? |
Character class followed by optional quantifier: matches a single character that is a hyphen, dot, or whitespace | - or . or space |
\d |
Matches a digit (0-9) | 4 |
{3} |
Quantifier: matches exactly 3 of the preceding token (digits) | 444 |
[-.\s]? |
Character class followed by optional quantifier: matches a single character that is a hyphen, dot, or whitespace | - or . or space |
\d |
Matches a digit (0-9) | 5 |
{4} |
Quantifier: matches exactly 4 of the preceding token (digits) | 5555 |
$ |
Anchor: asserts position at end of the string | End of string |
Matches
+1 (123) 456-7890123.456.78901234567890+44 20 7946 0958(123)4567890123-456-7890+99 123 456 7890123 456 7890
Does not match
12312345abc1234567+1234567890123123)456-7890(123-456-7890123.456.789123-456-789
Common pitfalls
- Overly permissive with separators (e.g., mixing hyphens and dots in the same number).
- Does not validate country codes (e.g., +999 is allowed but may not be valid).
- Allows invalid separators between groups (e.g., '123..456..7890').
- Does not enforce a minimum or maximum length for the entire string.
- May match strings with leading/trailing whitespace unless trimmed beforehand.
Performance notes
Low risk of catastrophic backtracking due to limited quantifiers and no nested quantifiers. Ensure input is trimmed to avoid leading/trailing whitespace issues. Anchors (^ and $) are critical for correctness.