精度为2的小数的正则表达式是什么?
有效的例子:
123.12
2
56754
92929292929292.12
0.21
3.1
无效的例子:
12.1232
2.23332
e666.76
小数点可以是可选的,也可以包括整数。
精度为2的小数的正则表达式是什么?
有效的例子:
123.12
2
56754
92929292929292.12
0.21
3.1
无效的例子:
12.1232
2.23332
e666.76
小数点可以是可选的,也可以包括整数。
当前回答
^[0-9]+(\.[0-9]{1,2})?$
因为正则表达式读起来很可怕,更不用说理解了,这里是详细的等效:
^ # Start of string
[0-9]+ # Require one or more numbers
( # Begin optional group
\. # Point must be escaped or it is treated as "any character"
[0-9]{1,2} # One or two numbers
)? # End group--signify that it's optional with "?"
$ # End of string
在大多数正则表达式实现中(包括最常见的PCRE),可以将[0-9]替换为\d。我把它保留为[0-9],因为我认为它更容易阅读。
此外,这是我用来检查它的简单Python脚本:
import re
deci_num_checker = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")
valid = ["123.12", "2", "56754", "92929292929292.12", "0.21", "3.1"]
invalid = ["12.1232", "2.23332", "e666.76"]
assert len([deci_num_checker.match(x) != None for x in valid]) == len(valid)
assert [deci_num_checker.match(x) == None for x in invalid].count(False) == 0
其他回答
这招对我很管用:
(-?[0-9]+(\.[0-9]+)?)
第一组是浮点数,第二组是分数。
你不需要考虑e666.76中的e吗?
With
(e|0-9)\d*\d.\d{1,2)
这将允许小数取幂和最多2位,
^[+-]?\d+(\.\d{2}([eE](-[1-9]([0-9]*)?|[+]?\d+))?)?$
Demo
preg_match("/^-?\d+[\.]?\d\d$/", $sum)
Chrome 56不接受这种模式(Chrome 56接受11.11。一个附加的。)与类型数字,使用类型作为文本作为进度。