如何在perl中验证数字? [英] How to validate number in perl?

查看:69
本文介绍了如何在perl中验证数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个图书馆可以做到这一点

I know that there is a library that do that

使用标量::Util qw(looks_like_number);

use Scalar::Util qw(looks_like_number);

但我想使用 perl 正则表达式来做.我希望它不仅适用于整数,而且适用于双数.

yet I want to do it using perl regular expression. And I want it to work for double numbers not for only integers.

所以我想要比这更好的东西

so I want something better than this

$var =~/^[+-]?\d+$/

$var =~ /^[+-]?\d+$/

谢谢.

推荐答案

构建单个正则表达式来验证数字真的很困难.有太多的标准需要考虑.Perlfaq4 包含如何确定标量是否为数字/整数/整数/浮点数?

Constructing a single regular expression to validate a number is really difficult. There simply are too many criteria to consider. Perlfaq4 contains a section "How do I determine whether a scalar is a number/whole/integer/float?

该文档中的代码显示了以下测试:

The code from that documentation shows the following tests:

if (/\D/)                          {print "has nondigits\n"      }
if (/^\d+$/)                       {print "is a whole number\n"  }
if (/^-?\d+$/)                     {print "is an integer\n"      }
if (/^[+-]?\d+$/)                  {print "is a +/- integer\n"   }
if (/^-?\d+\.?\d*$/)               {print "is a real number\n"   }
if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) {print "is a decimal number\n"}
if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) {
    print "is a C float\n"
}

  • 第一个测试取消了无符号整数的资格.
  • 第二个测试合格一个整数.
  • 第三个测试限定一个整数.
  • 第四个测试限定一个正/负符号整数.
  • 第五次测试合格一个实数.
  • 第六个测试合格一个十进制数.
  • 第七个测试限定了一个采用 c 风格科学记数法的数字.
  • 因此,如果您正在使用这些测试(不包括第一个),则必须验证一个或多个测试是否通过.那么你就有了一个号码.

    So if you were using those tests (excluding the first one) you would have to verify that one or more of the tests passes. Then you've got a number.

    另一种方法,既然不想使用Scalar::Util模块,可以参考代码IN Scalar::Util.look_like_number() 函数设置如下:

    Another method, since you don't want to use the module Scalar::Util, you can learn from the code IN Scalar::Util. The looks_like_number() function is set up like this:

    sub looks_like_number {
      local $_ = shift;
    
      # checks from perlfaq4
      return $] < 5.009002 unless defined;
      return 1 if (/^[+-]?\d+$/); # is a +/- integer
      return 1 if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/); # a C float
      return 1 if ($] >= 5.008 and /^(Inf(inity)?|NaN)$/i) 
               or ($] >= 5.006001 and /^Inf$/i);
    
      0;
    }
    

    您应该能够使用该功能中适合您情况的部分.

    You should be able to use the portions of that function that are applicable to your situation.

    不过,我想指出的是,Scalar::Util 是一个核心 Perl 模块;它与 Perl 一起提供,就像 strict 一样.最好的做法可能就是直接使用它.

    I would like to point out, however, that Scalar::Util is a core Perl module; it ships with Perl, just like strict does. The best practice of all is probably to just use it.

    这篇关于如何在perl中验证数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆