0

A phone number has exactly 11 digits, but there might be other readibility symbols in it, like spaces, brackets or hyphens.

Is it possible to match such numbers to one regex? Without any programming methods, just regex. E.g. all following numbers should match:

  • 71234567890
  • 7 123 4568790
  • 7(123)4567890
  • 7 (123) 456-78-90
  • 7(123) 456-7890

I suspect it might have something to do with positive lookahead. The regex might check if there are 11 digits, and then check if all the other symbols are from a certain set. But I haven't found a solution, so any idea would be greatly appreciated.

  • 1
    Just count the number of digit in the string. – ikleschenkov Aug 02 '17 at 13:15
  • 2
    Possible duplicate of [A comprehensive regex for phone number validation](https://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – marcusshep Aug 02 '17 at 13:17
  • Certainly seems like a very close question to this: https://stackoverflow.com/questions/16699007/regular-expression-to-match-standard-10-digit-phone-number – sniperd Aug 02 '17 at 14:03

2 Answers2

0

There are lots of ways to do this. And all kinds of interesting and good ways to do this on StackOverflow. Certainly you can do count just the numebers, (ignore hypens and parans), lots of cool ways. There probably isn't one 'best' way, if there is in the language you use there might already be a module for it.

If you simply have a list of numbers with extra stuff and you know this is the 'phone' list I would just strip out all non numbers, see if you get 11 numbers. Here is an example in Python:

import re

thelist = [
"71234567890",
"7 123 4568790",
"7(123)4567890",
"7 (123) 456-78-90",
"7(123) 456-7890",
]

for phone_dirty in thelist:
     phone_clean = re.sub("\D", "", phone_dirty)
     if len(phone_clean) == 11:
        print(phone_clean + " is a phone number")
     else:
        print(phone_clean + " is not a phone number")

You can have it check counts or do other kinds of verification. Really there are lots of ways to do this, this is just one.

sniperd
  • 5,124
  • 6
  • 28
  • 44
  • Yes, I totally understand it can be done with programming methods. I'm looking for **pure regex solution**. – Alexey Smirnov Aug 02 '17 at 13:50
  • Ah, I see. OK, I'd suggest hitting this one up: https://stackoverflow.com/questions/16699007/regular-expression-to-match-standard-10-digit-phone-number and just tweaking it a bit – sniperd Aug 02 '17 at 14:03
0
\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?\d[\(\)\-]?

Actually,

\d[\(\)\-]?

repeated 12 times