I
I
Ivan Ilyasov2015-11-28 10:47:18
Regular Expressions
Ivan Ilyasov, 2015-11-28 10:47:18

How to improve the regularity of a phone number?

Found a smart regular expression for a phone number: ^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7 ,10}$
I took it on Habré here: habrahabr.ru/post/110731
It turned out there is one problem. Does not validate such variations:
8 (900) 333-22-22
8 (900) 22-333-22
8 (900) 22-22-333
8 (900) 4444-333
8 (900) 22-22-333
8 (900) 333-1-333
And also with +7:
+7 (900) 333-22-22
+7 (900) 22-333-22
+7 (900) 22-22-333
+7 (900) 4444-333
+7 (900) 22-22-333
+7 (900) 333-1-333
And the same thing, only instead of a dash - a space:
8 (900) 333 22 22
8 (900) 22 333 22
8 (900) 22 22 333
8 (900) 4444 333
8 (900) 22 22 333
8 (900) 333 1 333
And also with +7:
+7 (900) 333 22 22
+7 (900) 22 333 22
+7 (900) 22 22 333
+7 (900) 4444 333
+7 (900) 22 22 333
+7 (900) 333 1 333
What to add? How to improve? Tell me please. I'm bad at this

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
neol, 2015-11-28
@neol

Is it important for you to save the numbers exactly as they were entered?
Personally, I prefer to discard everything that is not numbers, and check the resulting string: if it has 10 digits, then it can be a phone number.
As a bonus: operations with such standardized numbers are much easier for the DBMS, and you can output them in any convenient format.

V
vruzin, 2015-11-28
@vruzin

If we talk about user input and check for validity, then I didn’t see anything better than this andr-04.github.io/inputmask-multi/en.html
BUT, this is not a regular program, but a plugin for processing forms. Perhaps this is exactly what you need.

I
Ilya, 2015-11-28
@Gorily

Do you need to validate or parse from the text?
If validating, then I use libphonenumber ( https://github.com/googlei18n/libphonenumber) for these purposes , it is available for many programming languages. A very handy thing.
If we talk about regular expressions, then to extract from the text I use a similar one (C#):

new Regex(@"(7|8)?\s*(\(|-|\s)?\d{3}(\)|-|\s)?\s*\d{3}(-|\s)?\d{2}(-|\s)?\d{2}([^\d]|$)", RegexOptions.Compiled)

H
heartdevil, 2015-11-28
@heartdevil

Hello
Better use a strict mask. jquery plugin. Example . Click on demo.
Well, if you don’t process numbers in any way, then you don’t need to bathe.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question