简体   繁体   English

如何在Perl中创建仅匹配数字和小数点分隔符的正则表达式

[英]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.

相关问题 Ruby正则表达式将十进制数与百分比和仅十进制数匹配 - Ruby regex to match decimal number with percentage and only decimal numbers 正则表达式匹配十进制数 - Regex to match decimal number 正则表达式匹配以逗号作为分隔符的十进制数 - regex expression to match decimal numbers with comma as a separator 正则表达式检查数字小数分隔符是否一致 - Regex to check if a number decimal separator is consistent 如何编写用于法语数字格式的正则表达式? (空格为千位分隔符,逗号为十进制分隔符) - How can I write a Regex for French number formatting? (space as thousands separator, comma as decimal separator) 如何在 Perl 的正则表达式中只匹配一次 - How to match only once in a regex in Perl 使用正则表达式仅捕获数字或小数点分隔符 - Using regex to grab only digits or the decimal separator 用小数分隔符和可选的千位分隔符匹配数字的正则表达式 - Regular expression to match number with Decimal separator and optional Thousands separator 正则表达式匹配:1)整数,2)带小数的数字,小数后仅2位,或3)带小数的数字,小数后仅2位 - Regex to match either: 1)whole number, 2) number with fraction with only 2 digits after decimal or 3) fraction with only 2 digits after decimal JavaScript正则表达式:如何让oninput模式中只有2个十进制浮点数匹配? - JavaScript Regex: How to let only 2 decimal floating number through oninput pattern match?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM