Regular expression for positive decimal number with 0, 1 or 2 decimal places

后端 未结 5 1716
终归单人心
终归单人心 2021-01-16 11:48

Please help me make regular expression for positive decimal number with 0, 1 or 2 decimal places. It must allow comma and dot. For example it must allow:

0,0         


        
5条回答
  •  花落未央
    2021-01-16 12:22

    This will do what you want.

    I've added whitespace and comments and parentheses to clarify it:

    (                   #
      ( 0*[1-9]\d*   )  # a non-zero integer portion, followed by
      ( [\.,]\d{1,2} )? # an optional fraction of 1 or 2 decimal digits
    )                   # 
    |                   # OR
    (                   #
      ( 0+ )            # a zero integer portion, followed by
      (                 # an mandatory non-zero 1-2 digit fraction, consisting of
        [\.,]           # a decimal point
        (               # followed by 
          ( 0[1-9]   )  # a 0 followed by a 1-9,
          |             # OR
          ( [1-9]\d? )  # a 1-9 followed by an optional decimal digit
      )
    )
    

    The regular expression is suboptimal it something like 0000000000.01 will backtrack when it doesn't find a non-zero digit following the zeros in the integer portion, but it should work.

提交回复
热议问题