Simple regular expression for a decimal with a precision of 2

What is the regular expression for a decimal with a precision of 2?

Valid examples:

123.12
2
56754
92929292929292.12
0.21
3.1

Invalid examples:

12.1232
2.23332
e666.76

The decimal point may be optional, and integers may also be included.


Valid regex tokens vary by implementation. The most generic form that I know of would be:

[0-9]+(.[0-9][0-9]?)?

The most compact:

d+(.d{1,2})?

Both assume that you must have both at least one digit before and one after the decimal place.

To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):

^d+(.d{1,2})?$

ADDED: Wrapped the fractional portion in ()? to make it optional. Be aware that this excludes forms such as "12." Including that would be more like ^d+.?d{0,2}$ .


^[0-9]+(.[0-9]{1,2})?$

And since regular expressions are horrible to read, much less understand, here is the verbose equivalent:

^                         # 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

You can replace [0-9] with d in most regular expression implementations (including PCRE, the most common). I've left it as [0-9] as I think it's easier to read.

Also, here is the simple Python script I used to check it:

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

要包括一个可选的减号并且不允许数字如015 (可能被误认为八进制数字),请写下:

-?(0|([1-9]d*))(.d+)?
链接地址: http://www.djcxy.com/p/13396.html

上一篇: 正则表达式来搜索Gadaffi

下一篇: 对于精度为2的小数的简单正则表达式