Melinda Pereira
Melinda Pereira

Reputation: 29

Java regex for Uk phone numbers and phone codes

I looked a bit around the older posts but couldn't reeally find an answer for my case.

I have a regex

"(?:(?:(?:\+|00)44[\s\-\.]?)?(?:(?:\(?0\)?)[\s\-\.]?)?(?:\d[\s\-\.]?){10})" 

that matches the pattern below

+44 1642 468 592
+44-(0)207-54-60-022
(0)201 234 5678
0207 1345 678
01642.85.08.50

but not

(017683) 927 43

(0207) 1345-678

(0207) 1345 678

I did found a regex who works for the pattern (017683) 927 43 but I was wondering if this regex could be simplify to match phone numbers with 4, 5 or 6 digits between parenthesis ?

For pattern : (017683) 927 43

^\(0[0-9]{5}\) [0-9]{5}$|^\(01[0-9]{3}\) [0-9]{6}$|^\(01[0-9]1\)? [0-9]{3}? [0-9]{4}$

Upvotes: 2

Views: 1034

Answers (2)

davcs86
davcs86

Reputation: 3935

You can use

(?:(?:(?:\+|00)44[\s\-\.]?)?(?:(?:\(?0\)?)[\s\-\.]?)?(?:\d[\s\-\.]?){10})|(?=\(?\d*\)?[\x20\-\d]*)(\(?\)?\x20*\-*\d){11}

Demo here

Upvotes: 0

Daniel Gurianov
Daniel Gurianov

Reputation: 551

I would say , that You should not rely on the regex patterns in this case.

Basically , you should know number standard you are about to accept and this will tell you how much 0-9 digits you expect to consume from user input. Everything that is over or under is discarded and user is informed with "Please enter valid number".

To get amount of digits, you need to take user input and remove all non digit characters from it. This will standardize anything user enters :

+44123 456 789
+44-123-456-789
4412345 6789
44 123-456-789  

etc..

and even

+44 123-----456----789

to the same string 44123456789

After this done , if length of the string is matching with international standard , we can start to break it by positions to country code, city and analyze is there valid country , city , etc...

When you use regexp, you actually describing what symbols you agree to meet on positions from 0 to X. So if you expect to have "+,-,Nothing,[0-9]" as first element, you need to explicitly mention this in regexp expresion (\+\-[0-9]){0,1} .

And this is only for the first position!

If you expect 15 of those, this will make regexp completely unreadable not only by other people , but for you as well.

Upvotes: 4

Related Questions