Javascript 单仪表板电话号码-正则表达式验证
我需要一个简单的正则表达式来验证形式为x-y的电话号码,其中x和y可以表示任意数量的数字,破折号是可选的,但如果它确实出现,则大多数都在字符串中(破折号必须在其左右两侧有数字)Javascript 单仪表板电话号码-正则表达式验证,javascript,regex,Javascript,Regex,我需要一个简单的正则表达式来验证形式为x-y的电话号码,其中x和y可以表示任意数量的数字,破折号是可选的,但如果它确实出现,则大多数都在字符串中(破折号必须在其左右两侧有数字)/^\d+(?:-\d+)$/应该可以做到这一点。/^\d+(\d+)$/)似乎有效。它匹配一个或多个前导数字,并带有可选的“连字符后跟一个或多个数字” 给出: $ ./phone.pl "1-2" is a phone number "-12" is NOT a phone number "12-" is NOT a
/^\d+(?:-\d+)$/
应该可以做到这一点。/^\d+(\d+)$/)似乎有效。它匹配一个或多个前导数字,并带有可选的“连字符后跟一个或多个数字”
给出:
$ ./phone.pl
"1-2" is a phone number
"-12" is NOT a phone number
"12-" is NOT a phone number
"123-1234" is a phone number
"1-" is NOT a phone number
"-1" is NOT a phone number
"123" is a phone number
"1" is a phone number
"foo-bar" is NOT a phone number
"12foo34" is NOT a phone number
"foo12-34" is NOT a phone number
"12f-o34" is NOT a phone number
可能会发布到目前为止您做了什么?“1foobar”将被匹配,您应该约束字符串的开始和结束^…$@CMS:可能是真的,尽管iulianchira可能希望将其合并到更大的regexp中。调整答案。
$ ./phone.pl
"1-2" is a phone number
"-12" is NOT a phone number
"12-" is NOT a phone number
"123-1234" is a phone number
"1-" is NOT a phone number
"-1" is NOT a phone number
"123" is a phone number
"1" is a phone number
"foo-bar" is NOT a phone number
"12foo34" is NOT a phone number
"foo12-34" is NOT a phone number
"12f-o34" is NOT a phone number