-2

I want to be able to catch these type of phone formats

+xxx xxx xxx xxx
+xxx.xxx.xxx.xxx
+xxx xxxxxxxxx
+xxx-xxx-xxx-xxx
+xxxxxxxxxxxx
xxxx xxx xxx
xxxx xxxxxx
xxxx.xxx.xxx
xxxx-xxx-xxx
xxx-xxx-xxx
xxx.xxx.xxx
xxxxxxxxxx
xxxx xx xx xx
xxxx.xx.xx.xx
xxxx-xx-xx-xx

For the moment I am having this regex

/^[+]?(\d{1,2})?[\s.-]?\(?\d{4}\)?[\s.-]?\d{3}[\s.-]?\d{3}$/

which catches some of the examples, but no idea how to make it work for the other formats too

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
lStoilov
  • 1,256
  • 3
  • 14
  • 30
  • 1
    Just to point out the obvious - validating phone numbers with regexes might not be ideal. My phone number in the standard UK format wouldn't match any of the patterns above. Obviously that might not be relevant to you, but just in case :) – DaveyDaveDave May 21 '19 at 07:06
  • Yeap, That's just my case. I am sure it will not catch many other numbers :) – lStoilov May 23 '19 at 13:14

1 Answers1

0

These expressions are quite sensitive to design since all our possible inputs would not be in the list. Maybe, a better choice would be to only allow numbers, or removing all non-numeric chars first, and then process/validate that.

However, if we just wish to check based on the inputs listed here, we might be able to find an expression, maybe something similar to this:

^[+]?(\d{3,4})[\s.-]?(\d{2,9})?([\s.-])?(\d{2,3})[\s.-]?(\d{2,3})$

DEMO

enter image description here

RegEx

If this expression wasn't desired, it can be modified or changed in regex101.com.

RegEx Circuit

jex.im also helps to visualize the expressions.

enter image description here

JavaScript Demo

This snippet is just to show that how the capturing groups work:

const regex = /^[+]?(\d{3,4})[\s.-]?(\d{2,9})?([\s.-])?(\d{2,3})[\s.-]?(\d{2,3})$/mg;
const str = `+777 777 777 777
+777.777.777.777
+777 777777777
+777-777-777-777
+777777777777
7777 777 777
7777 777777
7777.777.777
7777-777-777
777-777-777
777.777.777
7777777777
7777 77 77 77
7777.77.77.77
7777-77-77-77`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
Emma
  • 27,428
  • 11
  • 44
  • 69