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, etc 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?
我正在尝试验证一个(US)电话号码,其中没有附加字符。所以格式是1-555-555-5555,没有破折号、空格等,1是可选的。但是,我的正则表达式将只包含前导1的数字,并说没有前导1的数字无效。这是我用的东西哪里出错了?
"^(1)\\d{10}$"
3 个解决方案
#1
29
Use:
使用:
"^1?\\d{10}$"
The ? means "optional".
的吗?意思是“可选的”。
#2
14
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成为可选的。你把它放在一个组里,但仅此而已。你想要这样的:
"^1?\\d{10}$"
That basically says to match (in this order):
也就是说匹配(按这个顺序)
- The start of the string
- 弦的开始
- Optionally the character '1'
- 可选字符' 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:
查看Pattern的文档了解更多细节。例如,?列于“贪心量词”一栏如下:
X? X, once or not at all
X ?X,一次或者根本没有
#3
2
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.
使用这一个“/ ^((\ + ? 1 -[2 - 9]\ d { 2 } -[2 - 9]\ d { 2 } \ d { 4 })|(\[2 - 9](\ d { 2 } \)(\ s)?[2 - 9]\ d { 2 } - \ d { 4 }))$ / ",它将只允许US-allowed数字包括“1-xxx-xxx-xxxx”、”(xxx)xxx-xxxx + 1-xxx-xxx-xxxx”。我希望这就是你要找的。
#1
29
Use:
使用:
"^1?\\d{10}$"
The ? means "optional".
的吗?意思是“可选的”。
#2
14
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成为可选的。你把它放在一个组里,但仅此而已。你想要这样的:
"^1?\\d{10}$"
That basically says to match (in this order):
也就是说匹配(按这个顺序)
- The start of the string
- 弦的开始
- Optionally the character '1'
- 可选字符' 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:
查看Pattern的文档了解更多细节。例如,?列于“贪心量词”一栏如下:
X? X, once or not at all
X ?X,一次或者根本没有
#3
2
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.
使用这一个“/ ^((\ + ? 1 -[2 - 9]\ d { 2 } -[2 - 9]\ d { 2 } \ d { 4 })|(\[2 - 9](\ d { 2 } \)(\ s)?[2 - 9]\ d { 2 } - \ d { 4 }))$ / ",它将只允许US-allowed数字包括“1-xxx-xxx-xxxx”、”(xxx)xxx-xxxx + 1-xxx-xxx-xxxx”。我希望这就是你要找的。