[英]make characters optional in regular expression
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.
因此格式为1-555-555-5555,没有短划线,空格等,1是可选的。 However, my regular expression will ONLY except numbers with the leading 1 and says numbers without it are invalid.
但是,我的正则表达式只有前导1的数字和没有它的数字都是无效的。 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. 你没有做任何让 1选择的东西。 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): 这基本上说匹配(按此顺序):
Look at the documentation for Pattern
for more details. 有关详细信息,请查看
Pattern
的文档 。 For example, ?
例如,
?
is listed in the "Greedy Quantifiers" section like this: 列在“贪婪量词”部分中,如下所示:
X?
X? X, once or not at all
X,曾经或根本没有
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. 使用这个
"/^((\\+?1-[2-9]\\d{2}-[2-9]\\d{2}-\\d{4})|(\\([2-9]\\d{2}\\)(\\s)?[2-9]\\d{2}-\\d{4}))$/"
它只允许美国允许的数字,包括”1-xxx-xxx- xxxx“,”+ 1-xxx-xxx-xxxx“,(xxx)xxx-xxxx。 I hope this is what you looking for. 我希望这就是你要找的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.