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
2 Answers
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