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)
"1foobar" will be matched, you should constraint the start and end of the string ^...$
CMS
2009-10-15 20:50:40
@CMS: probably true, although iulianchira may be looking to incorporate this in a larger regexp. Tweaked answer.
moonshadow
2009-10-15 20:54:21
+1
A:
/^\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
khearn
2009-10-16 00:50:20