Last active
September 20, 2020 14:05
-
-
Save peyerluk/8357036 to your computer and use it in GitHub Desktop.
Format swiss phone number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# validating samples: | |
# 783268674 | |
# 0783268674 | |
# 0410783268674 | |
# 00410783268674 | |
# +410783268674 | |
# 041783268674 | |
# 0041783268674 | |
# +41783268674 | |
# ++41783268674 | |
# ++41(0)783268674 | |
# (0)783268674 | |
swissPhoneRegex: /^(0041|041|\+41|\+\+41|41)?(0|\(0\))?([1-9]\d{1})(\d{3})(\d{2})(\d{2})$/ | |
# swissPhoneRegex is setup so we can also use it to format valid phone numbers consistently | |
formatPhoneNumber: (phone) -> | |
# regex is set up so we can easily format the matching parts | |
phone = phone.replace(/[\s()]/g, "") | |
res = @swissPhoneRegex.exec(phone) | |
if res then "0#{ res[3] } #{ res[4] } #{ res[5] } #{ res[6] }" else "" |
Da kollegä :D
^(0|0041|\+41)?[1-9\s][0-9\s]{1,12}$
matched au mit leerstelle
Da kollegä :D
^(0|0041|\+41)?[1-9\s][0-9\s]{1,12}$
Merci!
^(0|0041|\+41)?[1-9\s][0-9\s]{1,12}$
feels too greedy. For example, it matches 05
.
Btw, hi @peyerluk 👋 Nice to find your content when searching the interwebs 🙏
I have settled on this for the moment:
const internationalPhoneRegexp = /((\+|00)\d{8,30})/;
// Works for formatted mobile phone numbers like "078 326 86 74"
const swissPhoneRegexp1 = /(0[1-9]{2}\s[0-9]{3}\s[0-9]{2}\s[0-9]{2})/;
// Works for unformatted mobile phone numbers like "0783268674" and
// unformatted landline numbers like "041783268675"
const swissPhoneRegexp2 = /(0[0-9]{9,11})/;
const fullRegexp = new RegExp(
[
internationalPhoneRegexp.source,
swissPhoneRegexp1.source,
swissPhoneRegexp2.source,
].join('|'),
'g'
);
It's not perfect, and will miss some formatting of phone numbers. However, it's less greedy, works for the formatted numbers that I currently care about and can be used without stripping whitespace.
It works for these test numbers:
- 0783268674
- 078 326 86 74
- 041783268675
- 0041783268674
- +41783268676
- +41783268677
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Needed a break from studying. Here's a stricter and compacter regex:
Take a look an non-capturing groups as they don't pollute your matches:
(?:a|b)
instead of(a|b)
.Here's a visualization of the regexp 😉