I am trying to validate a (US) phone number with no extra characters in it. so the format is 1-555-555-5555 with no dashes, spaces, e开发者_JAVA百科tc and the 1 is optional. However, my regular expression will ONLY except numbers with the leading 1 and says numbers without it are invalid. Here is what I am using where did I go wrong?
"^(1)\\d{10}$"
Use:
"^1?\\d{10}$"
The ? means "optional".
You haven't done anything to make the 1 optional. You've put it in a group, but that's all. You want this:
"^1?\\d{10}$"
That basically says to match (in this order):
- The start of the string
- Optionally the character '1'
- Exactly ten digits
- The end of the string
Look at the documentation for Pattern
for more details. For example, ?
is listed in the "Greedy Quantifiers" section like this:
X? X, once or not at all
Use this one "/^((\+?1-[2-9]\d{2}-[2-9]\d{2}-\d{4})|(\([2-9]\d{2}\)(\s)?[2-9]\d{2}-\d{4}))$/"
It will allow only US-allowed numbers which include "1-xxx-xxx-xxxx","+1-xxx-xxx-xxxx",(xxx) xxx-xxxx. I hope this is what you looking for.
精彩评论