Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - simple phone number

Tags:

regex

I know there are a ton of regex examples on how to match certain phone number types. For my example I just want to allow numbers and a few special characters. I am again having trouble achieving this.

Phone numbers that should be allowed could take these forms

5555555555
555-555-5555
(555)5555555
(555)-555-5555
(555)555-5555 and so on

I just want something that will allow [0-9] and also special characters '(' , ')', and '-'

so far my expression looks like this

/^[0-9]*^[()-]*$/

I know this is wrong but logically I believe this means allow numbers 0-9 or and allow characters (, ), and -.

like image 921
IamBanksy Avatar asked Feb 04 '23 03:02

IamBanksy


2 Answers

^(\(\d{3}\)|\d{3})-?\d{3}-?\d{4}$
  • \(\d{3}\)|\d{3} three digits with or without () - The simpler regex would be \(?\d{3}\)? but that would allow (555-5555555 and 555)5555555 etc.
  • An optional - followed by three digits
  • An optional - followed by four digits

Note that this would still allow 555555-5555 and 555-5555555 - I don't know if these are covered in your and so on part

like image 173
Amarghosh Avatar answered Feb 06 '23 09:02

Amarghosh


This match what you want numbers,(, ) and -

/^[0-9()-]+$/
like image 31
Toto Avatar answered Feb 06 '23 10:02

Toto