kjv
kjv

Reputation: 11327

Single dash phone number - regex validation

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)

Upvotes: 0

Views: 3000

Answers (2)

khearn
khearn

Reputation: 31

/^\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

Upvotes: 1

moonshadow
moonshadow

Reputation: 89115

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

Upvotes: 6

Related Questions