单个短划线电话号码 - 正则表达式验证

时间:2009-10-15 20:41:09

标签: javascript regex

我需要一个简单的正则表达式来验证xy格式的电话号码,其中x和y可以表示任意数量的数字,短划线是可选的,但是如果它确实显示出来,则大多数都在字符串内(短划线必须左侧和右侧有数字)

2 个答案:

答案 0 :(得分:6)

/^\d+(?:-\d+)?$/应该可以解决问题。

答案 1 :(得分:1)

/ ^ \ d +( - \ d +)?$ /)似乎有效。它匹配一个或多个前导数字,可选“连字符后跟一个或多个数字”。

#!/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";
  }
}

给出:

$ ./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