我需要一个简单的正则表达式来验证形式为xy的电话号码,其中x和y可以表示任意数字,而破折号是可选的,但是如果确实显示,则大多数出现在字符串中(破折号必须在数字处它的左和右)
/^\\d+(?:-\\d+)?$/
应该可以解决问题。
/^\\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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.