I need your help! I need a regex, that matches the following phone number formats (Germany, Austria, Switzerland). I have no idea, how to create this regex.
What I need are phone number formats as follows:
+49 (089) 1234567890
+43 (01) 1234567890
+41 (051) 1234567890
Only the mentioned country codes (+49, +43, +41) can be filled in this way (including plus sign). No 0049 or (0049) or (+49) etc.
Subsequent a space character should be between the country code and the area code. No other characters like -, /, + etc. or letters are allowed. Only space character.
The following area code must have brackets.
Subsequent a space character should also be between the area code and the phone number. No other characters like -, /, + etc. or letters are allowed. Only space character.
The phone number should be filled in its entirety (only numbers are possible and there are no spaces between the numbers).
I hope, someone can support me and my request, because I really don't know how to create this expression. I tried it and that is the result:
[0-9]*\/*(\+49)*(\+43)*(\+41)*[ ]*(\([0-9]{3,6}\))*([ ]*[0-9]|\/|\(|\)|\-|)*
I guess, this is totally wrong.
Best regards, Klaus
This should work for the Germany, Austria, and Switzerland. First three are valid, the remaining ones are invalid for testing:
const regex = /^\+4[139] \(0\d+\) \d{9,}$/;
[ '+49 (089) 1234567890',
'+43 (01) 1234567890',
'+41 (051) 1234567890',
'+41 (0) 1234567890',
'+41 (12) 1234567890',
'+41 (051) 12',
'+41 (051)',
'+41 051 1234567890',
'+41-051-1234567890',
'+44 (051) 1234567890',
].forEach(str => {
console.log(str + ' ==> ' + regex.test(str));
});
Output:
+49 (089) 1234567890 ==> true
+43 (01) 1234567890 ==> true
+41 (051) 1234567890 ==> true
+41 (0) 1234567890 ==> false
+41 (12) 1234567890 ==> false
+41 (051) 12 ==> false
+41 (051) ==> false
+41 051 1234567890 ==> false
+41-051-1234567890 ==> false
+44 (051) 1234567890 ==> false
Explanation:
^
- anchor at start of string (disallow anything before)\+
- literal '+'4[139]
- a 41
, 43
, or 49
- space\(0\d+\)
- a number starting with 0
and at least two digits, enclosed in parenthesis
- space\d{9,}
- a number with at least 9 digits (you can restrict both, for example \d{9,12}
is a number with 9 to 12 digits)$
- anchor at end of string (disallow anything after)