[英]What's the shortest regex that can match non-zero floating point numbers with any number of decimal places?
What's the shortest regex that can match non-zero floating point numbers with any number of decimal places?可以匹配具有任意小数位的非零浮点数的最短正则表达式是什么?
It should accept numbers like它应该接受像这样的数字
-1
-5.9652
-7.00002
-0.8
-0.0500
-0.58000
0.01
0.000005
0.9900
5
7.5
7.005
but reject constructions such as但拒绝结构,如
.
.02
-.
-.996
0
-0
0.
-0.
-0.000
0.00
--
..
+
+0
+1
+.
+1.26
,etc
I do not need support for the scientific notation, with e , E and such.我不需要支持科学记数法,如 e 、 E 等。
The language I'm using is C#, by the way.顺便说一下,我使用的语言是 C#。
^-?(0\.\d*[1-9]|[1-9]\d*(\.\d+)?)$
EDIT Updated to reflect new requirements (last decimals can be zero)编辑更新以反映新要求(最后一位小数可以为零)
^-?(0\.\d*[1-9]\d*|[1-9]\d*(\.\d+)?)$
(Shorter than using lookahead: ^-?(0\\.(?=[1-9])\\d*|[1-9]\\d*(\\.\\d+)?)$
.) (比使用前瞻更短:
^-?(0\\.(?=[1-9])\\d*|[1-9]\\d*(\\.\\d+)?)$
。)
EDIT2 If eg 001.000
can pass EDIT2如果例如
001.000
可以通过
^-?(?=.*[1-9])\d+(\.\d+)?$
This is the one I always use:这是我经常使用的:
(\\+|-)?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE](\\+|-)?[0-9]+)?
Utilized in a PHP example:在 PHP 示例中使用:
<?php
$s= '1.234e4';
preg_match('~(\+|-)?([0-9]+\.?[0-9]*|\.[0-9]+)([eE](\+|-)?[0-9]+)?~', $s, $m);
print_r($m);
?>
Output:输出:
Array
(
[0] => 1.234e4
[1] =>
[2] => 1.234
[3] => e4
)
-?(?!0)\d+(\.\d+)?
Note: Remember to put ^ $ if it's not done by your regexp matcher.注意:如果您的正则表达式匹配器没有完成,请记住放置 ^ $。
May I ask why the "shortest"?请问为什么是“最短”? A pre-compiler RegExp or the same with non-matching groups could be faster.
带有非匹配组的预编译器 RegExp 或相同的可能会更快。 Also a test for zero could possibly be faster too.
零测试也可能更快。
您可能希望考虑这些变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.