[英]How to create a regex that match only number and decimal separator in Perl
I want to have a regex that reject string that contain any alphabets. 我想有一个正则表达式拒绝包含任何字母的字符串。 But allow numbers like: 4, 4.5, 12.330 but not 12.2.3.4 (multiple dots).
但是允许使用以下数字:4、4.5、12.330,但不允许使用12.2.3.4(多点)。
But why this regex of mine failed? 但是为什么我的这个正则表达式失败了?
my $str1 = $ARGV[0] || "foo1";
if ($str1 =~ /^[\d+]|[^a-zA-Z]+|[\.]\d+$/) {
print "This is strictly numeric: $str1\n";
}
else {
print "This contain alphabet\n";
}
The input still pass first condition which I don't want. 输入仍然通过我不想要的第一个条件。
Running example here: https://eval.in/73654 在此处运行示例: https : //eval.in/73654
if ($str1 =~ /^\d+(?:\.\d+)?$/) { ... }
如果您还希望以小数点分隔符结尾且没有后跟数字的字符串,请使用
if ($str1 =~ /^\d+(?:\.\d*)?$/) { ... }
I think you need parens around your ors: 我认为您需要在您的ors周围做一些事情:
if ( $str1 =~ /^([\d+]|[^a-zA-Z]+|[\.]\d+)$/ ) {
also 也
[^a-zA-Z]+
will match everything that \\d+
or \\.\\d+
would. [^a-zA-Z]+
将匹配\\d+
或\\.\\d+
。
also 也
you could write the first and last terms as simply \\.?\\d+
您可以将第一个和最后一个术语写为
\\.?\\d+
but really, that's not what you want since you also want 4.5 which would match against something like \\d+\\.?\\d*
但实际上,这不是您想要的,因为您还希望4.5与
\\d+\\.?\\d*
类的东西匹配\\d+\\.?\\d*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.