Simple regular expression for a decimal with a precision of 2

后端 未结 17 2317
闹比i
闹比i 2020-11-22 02:02

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
17条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 02:56

    For numbers that don't have a thousands separator, I like this simple, compact regex:

    \d+(\.\d{2})?|\.\d{2}
    

    or, to not be limited to a precision of 2:

    \d+(\.\d*)?|\.\d+
    

    The latter matches
    1
    100
    100.
    100.74
    100.7
    0.7
    .7
    .72

    And it doesn't match empty string (like \d*.?\d* would)

提交回复
热议问题