views:

94

answers:

4

I need help writing a regex for a phone number pattern that allows the following formats for a phone number


1)###-###-####
or 
2)#-###-###-####
or
3)###-####
or
4)##########
or
5)#######

I am well aware, that you are able to find regex patterns on the internet, but I havent been able to find one that will pass for all these patterns.

I am using Java

+2  A: 

You could use the | (or) operator and multiple patterns.

For example: (\d{7})|(\d{10)| ...

Jeanne Boyarsky
yeah I am aware of this use, but I do not have all the patterns
CitadelCSAlum
wait... if you don't know what you're looking for then how will you know when you find it? ~plato
gnucom
+2  A: 

try ^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$

Here is an online regular expression evaluator, you can test your patterns against this regex and/or any other.

StudiousJoseph
+1  A: 

Try this regular expression:

@"^(((\d-)?\d{3}-)?(\d{3}-\d{4})|\d{7}|\d{10})$"

This covers the five scenarios you've described; Alternatively, if you can also accept the following scenarios:

6)###-#######
or 
7)#-###-#######
or 
8)#-##########

Then this shorter variant will work also:

@"^(((\d-?)?\d{3}-?)?(\d{3}-?\d{4}))$"

robyaw
+1  A: 

Try this

^\d?-?(\d{3})?-?\d{3}-?\d{4}$

kuroutadori