0

So, after some user confusion, I need to tweak a regular expression for all phone number variations you could think of.

I currently have the following regular expression:

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

It matches fairly well, but I'd like to be able to match this to the following variations:

  • +44 01726 400480

  • +44 1726 400480

  • +44 01726 400 480

  • +44 1726 400 480

  • 01726 400480

  • 01726 400 480

N.B. I understand that similar questions to this have been asked previously, but I feel that adding the above variations would be perfect for the community.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Micheal J. Roberts
  • 3,735
  • 4
  • 37
  • 76
  • @AndrewMorton Without sounding belligerent, I don't think this is duplicate because the matches I can see on other questions do not cover all of the outlying cases. – Micheal J. Roberts Oct 08 '18 at 14:38
  • @Cerbrus Without sounding belligerent, I don't think this is duplicate because the matches I can see on other questions do not cover all of the outlying cases. – Micheal J. Roberts Oct 08 '18 at 14:38

2 Answers2

3

You can use

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

https://regex101.com/r/DiJLVb/2

Note that [0-9] simplifies to \d, and that character sets with only a single character in them simplify to just that character. Also note that using a literal space is a bit more reliable than \s if you only want to match a literal space - otherwise, other whitespace characters like newlines will be matched too, which may well not be desirable.

Details:

  • \+? - Optional plus
  • (?:[- .]?\d{2})? - Optional leading two digits
  • [- .]?\d{4,5} - Four or five digits
  • [- .]?\d{3}[- .]?\d{3} - Six digits, possibly separated by a character
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

you can try the following https://www.regexpal.com/?fam=105302

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

forgetso
  • 2,194
  • 14
  • 33