如何使用正则表达式断言标量只有数字但没有字母字符?

时间:2012-05-30 07:06:59

标签: perl

我希望与变量$x = 'AA12CB'匹配。我正在使用正则表达式

$x =~ /\b[0-9]+\b/

我想断言我只有数字,但不是字母字符。这个正则表达式无效。

4 个答案:

答案 0 :(得分:4)

您需要在字符串的开头和结尾锚定模式以排除任何其他字符。这类似于您尝试使用\b边界的内容。请阅读perlretut了解锚定的含义,它会出现几次。

use 5.010;
my $x = 'AA12CB';
if ($x =~ /\A [0-9]+ \z/msx) {
    say 'only digits'
} else {
    say 'not only digits'
}

也许你更想要to determine whether a scalar is a number/whole/integer/float

答案 1 :(得分:2)

我认为对于没有行尾的字符串,此表达式最能捕获该标准:

$x !~ /\D/

这意味着$x在任何时候都不匹配非数字字符。当然,如果你仍然想要一个非chomp ed字符串的行结尾,那么你必须使用负字符类,如下所示:

$ x!〜/ [^ \ d \ n] /

$x与字符不是数字或换行符的字符串不匹配。

答案 2 :(得分:1)

这也适用于Perl。

$x = "AA12CB";
unless($x=~m/\D/) {
  print("$x: Just digits\n");
}
else {
  print("$x: Not just digits\n\n");
}

$x = "1223456";
unless($x=~m/\D/) {
  print("$x: Just digits\n");
}
else {
  print("$x: Not just digits\n");
}

\D是关键所在。它匹配任何不是数字的东西。您可以轻松将其写为ifelse,而不是unlesselse

答案 3 :(得分:1)

如果您刚刚进行了数字测试,Scalar::Utillooks_like_number函数就足够了:

use Scalar::Util 'looks_like_number';

print   looks_like_number( $x )
      ?   "$x is numeric\n"
      :   "$x is non-numeric\n";

我认为您的应用程序中不会遇到奇怪的'0 but true' ......