我需要编写一个正则表达式,只允许正数(整数或小数)。我发现了这个:
/^(?!(?:0|0\.0|0\.00)$)[+]?\d+(\.\d|\.\d[0-9])?$/
但它只接受最多2位小数。我必须做出哪些更改,以便它可以接受任意数量的小数位?
另外,我在哪里可以找到学习正则表达式的好教程。
事先谢谢
答案 0 :(得分:9)
这将是我的方式:^[+]?\d+([.]\d+)?$
编辑:如果您想允许.23
之类的内容,可以使用^[+]?([.]\d+|\d+([.]\d+)?)$
编辑: tchrist 坚持这一点:允许4.
,您可以使用^[+]?([.]\d+|\d+[.]?\d*)$
说明:
注意:这不会接受负数,这是您最终想要的。
答案 1 :(得分:6)
简短的回答是你需要这种模式:
^(?!(?:^[-+]?[0.]+(?:[Ee]|$)))(?!(?:^-))(?:(?:[+-]?)(?=[0123456789.])(?:(?:(?:[0123456789]+)(?:(?:[.])(?:[0123456789]*))?|(?:(?:[.])(?:[0123456789]+))))(?:(?:[Ee])(?:(?:[+-]?)(?:[0123456789]+))|))$
长答案包含在以下程序中:
#!/usr/bin/perl
use strict;
use warnings qw<FATAL all>;
my $number_rx = qr{
# leading sign, positive or negative
(?: [+-] ? )
# mantissa
(?= [0123456789.] )
(?:
# "N" or "N." or "N.N"
(?:
(?: [0123456789] + )
(?:
(?: [.] )
(?: [0123456789] * )
) ?
|
# ".N", no leading digits
(?:
(?: [.] )
(?: [0123456789] + )
)
)
)
# abscissa
(?:
(?: [Ee] )
(?:
(?: [+-] ? )
(?: [0123456789] + )
)
|
)
}x;
my $negative_rx = qr{ ^ - }x;
my $zero_rx = qr{ ^ [-+]? [0.]+ (?: [Ee] | $ ) }x;
my $positive_rx = qr{
^
(?! $zero_rx )
(?! $negative_rx )
$number_rx
$
}x;
my @test_data = qw{
-2 2 +2 2. -1 1 +1 1.
0 +0 -0 .0 0.
1.3 -3.2 5.13.7
00.00 +00 -00 +0-1
0000.
McGillicuddy
+365.2425
6.02e23
.0000000000000000000000000000000000000000000000000000000000000000000
.00000000000000000000000000000000000000000000000000000000000000000000000001
.03 0.3 3.0
0e50 0e-50
1e50 1e+50 1e-50
};
for my $n (@test_data) {
printf "%s is%s a positive number.\n",
$n, $n =~ /$positive_rx/ ? "" : " not";
}
测试结果如下:
-2 is not a positive number.
2 is a positive number.
+2 is a positive number.
2. is a positive number.
-1 is not a positive number.
1 is a positive number.
+1 is a positive number.
1. is a positive number.
0 is not a positive number.
+0 is not a positive number.
-0 is not a positive number.
.0 is not a positive number.
0. is not a positive number.
1.3 is a positive number.
-3.2 is not a positive number.
5.13.7 is not a positive number.
00.00 is not a positive number.
+00 is not a positive number.
-00 is not a positive number.
+0-1 is not a positive number.
0000. is not a positive number.
McGillicuddy is not a positive number.
+365.2425 is a positive number.
6.02e23 is a positive number.
.0000000000000000000000000000000000000000000000000000000000000000000 is not a positive number.
.00000000000000000000000000000000000000000000000000000000000000000000000001 is a positive number.
.03 is a positive number.
0.3 is a positive number.
3.0 is a positive number.
0e50 is not a positive number.
0e-50 is not a positive number.
1e50 is a positive number.
1e+50 is a positive number.
1e-50 is a positive number.
答案 2 :(得分:2)
答案 3 :(得分:-1)
这很简单-/\d*(\.d*)?/g
更新:该字符串与空字符串不匹配-/(\.)?\d+(\.\d*)?/g
在“-1.5 0 12. -123.4。15 -2。.4”