Regex for telephone numbers with specific prefixes

Viewed 158

I'm created this regex to match telephone numbers that have three specific prefixes, but it's not perfect. I need a regex that will only match numbers with the prefixes +48, +420, 421 and nothing else.

^[+][4](8|2)[0-9]{1,14}\d

When the Input is +421 456 456 456ioejkfoi312 I want the regular expression to match +421 456 456 456.

1 Answers

I think this works perfectly.

console.log(/\+420\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|\+421\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|48\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}/.test("+48123")) // true
console.log(/\+420\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|\+421\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|48\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}/.test("+420 123")) // true
console.log(/\+420\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|\+421\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|48\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}/.test("+421 12 3")) // true
console.log(/\+420\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|\+421\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|48\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}/.test("+422123")) // false
console.log(/\+420\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|\+421\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|48\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}/.test("+41123")) // false
console.log(/\+420\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|\+421\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}|48\s*\d{1,5}\s*\d{1,5}\s*\d{1,5}/.test("+421456456456")) // true

Anything else gives false

Related