perl 判断是否数字
答案:3 悬赏:30 手机版
解决时间 2021-03-13 02:04
- 提问者网友:椧運幽默
- 2021-03-12 22:38
perl 判断是否数字
最佳答案
- 五星知识达人网友:零点过十分
- 2021-03-12 22:48
数字有很多种.. 以下示范是所有合理数字的判断:
my @test = ( "-0", "0123", 1, "1.0", 2.23, "2.3.3", -10, -10.5, "-10.5.5" ) ;
my $reg1 = qr/^-?d+(.d+)?$/;
my $reg2 = qr/^-?0(d+)?$/;
foreach my $num ( @test ) {
my $is = undef;
$is = "is" if ( $num =~ $reg1 && $num !~ $reg2 );
$is = "is not" unless $is;
print "$num $is a number$/";
}
__END__
结果如下:
-0 is not a number
0123 is not a number
1 is a number
1.0 is a number
2.23 is a number
2.3.3 is not a number
-10 is a number
-10.5 is a number
-10.5.5 is not a number
但如果你只需要检验输入的为纯数字, 那就可以简单点:
my $num = "01234567";
print "yes" if $num =~ /^d+$/;
my @test = ( "-0", "0123", 1, "1.0", 2.23, "2.3.3", -10, -10.5, "-10.5.5" ) ;
my $reg1 = qr/^-?d+(.d+)?$/;
my $reg2 = qr/^-?0(d+)?$/;
foreach my $num ( @test ) {
my $is = undef;
$is = "is" if ( $num =~ $reg1 && $num !~ $reg2 );
$is = "is not" unless $is;
print "$num $is a number$/";
}
__END__
结果如下:
-0 is not a number
0123 is not a number
1 is a number
1.0 is a number
2.23 is a number
2.3.3 is not a number
-10 is a number
-10.5 is a number
-10.5.5 is not a number
但如果你只需要检验输入的为纯数字, 那就可以简单点:
my $num = "01234567";
print "yes" if $num =~ /^d+$/;
全部回答
- 1楼网友:西风乍起
- 2021-03-13 01:03
我猜你的意思是判断某个字符串中是不是只有数字?
可以用正则
if $str =~ m/^\d+$/
...
$str就是你要测试的字符串
可以用正则
if $str =~ m/^\d+$/
...
$str就是你要测试的字符串
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯