Regex: Phone number (E.164)
E.164 is the international format that telephone networks and SMS APIs expect: a +, the country code, then the number, at most 15 digits in all and no spaces. +14155552671 is a US number, +48123456789 a Polish one.
Pattern
^\+[1-9]\d{1,14}$ How it works
- ^
- Start of the string.
- \+
- A literal plus sign.
- [1-9]
- The first digit of the country code: never 0.
- \d{1,14}
- One to fourteen more digits, so 2 to 15 in all.
- $
- End of the string.
Matches
- +14155552671
- +48123456789
- +442071838750
Doesn't match
- 0048123456789
- +0123456
- +1 415 555 2671
- +1234567890123456
In your language
- JavaScript
/^\+[1-9]\d{1,14}$/A literal;
new RegExp(source, flags)builds the same from a string.- Python
re.compile(r"^\+[1-9]\d{1,14}$", re.ASCII)A raw string, so backslashes reach
reas written.re.ASCIIkeeps\dto0-9, as in JavaScript (Python matches any Unicode digit otherwise). Usere.fullmatchto test a whole string.- Java
Pattern.compile("^\\+[1-9]\\d{1,14}$")A normal string literal, so every backslash is doubled.
matcher(s).matches()tests the whole string.- Go
regexp.MustCompile(`^\+[1-9]\d{1,14}$`)A raw string in backticks. RE2 runs in linear time but has no lookaround and no backreferences.
- PHP
preg_match('/^\+[1-9]\d{1,14}$/D', $input)PCRE with
/delimiters inside a single-quoted string. Without theDmodifier,$also matches before a final newline, so it is added to patterns that end in$.- C#
new Regex(@"^\+[1-9]\d{1,14}$", RegexOptions.ECMAScript)A verbatim string: backslashes stay, a quote is doubled.
RegexOptions.ECMAScriptkeeps\dto0-9, as in JavaScript.$also matches before a final newline; to reject one, end the pattern with\zinstead.
Common mistakes
Strip formatting first
People write
+1 (415) 555-2671. Remove spaces, dashes, dots and brackets before matching, rather than making the pattern accept them.Shape is not existence
The pattern checks the length and the first digit only. Whether a number can exist depends on the country's numbering plan; Google's libphonenumber knows each one.
National numbers need a country
A number typed without
+(0612345678) can only become E.164 if you know which country it is from. Ask for the country, or default to the user's.