最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Single dash phone number - regex validation - Stack Overflow

programmeradmin0浏览0评论

I need a simple regex to validate a phone number of the form x-y, where x and y can represent any number of digits and the dash is optional, but if it does show up it most be within the string (the dash must have digits at its left and right)

I need a simple regex to validate a phone number of the form x-y, where x and y can represent any number of digits and the dash is optional, but if it does show up it most be within the string (the dash must have digits at its left and right)

Share Improve this question asked Oct 15, 2009 at 20:41 kjvkjv 11.3k35 gold badges102 silver badges141 bronze badges 1
  • 1 Maybe post what have you so far? – Dana Commented Oct 15, 2009 at 20:42
Add a ment  | 

2 Answers 2

Reset to default 6

/^\d+(?:-\d+)?$/ should do the trick.

/^\d+(-\d+)?$/) seems to work. It matches one or more leading digits, with an optional "hyphen followed by one or more digits".

#!/usr/bin/perl
#
@A = ( "1-2",
       "-12",
       "12-",
       "123-1234",
       "1-",
       "-1",
       "123",
       "1",
       "foo-bar",
       "12foo34",
       "foo12-34",
       "12f-o34",
       );

foreach (@A) {
  if (/^\d+(-\d+)?$/) {
    print "\"$_\" is a phone number\n";
  } else{
    print "\"$_\" is NOT a phone number\n";
  }
}

gives:

$ ./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
发布评论

评论列表(0)

  1. 暂无评论