冉冉说
^[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你可以代替[0-9]带着\d在大多数正则表达式实现中(包括PCRE,最常见)。我把它当作[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