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

后端 未结 5 1718
终归单人心
终归单人心 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

    Edit 2: now disallows exactly 0,0.0, etc.

    This matches at least one digit before the decimal place, followed by an optional decimal place, followed by 0-2 digits.

    The negative lookahead looks for any flavor of absolute zero and prevents a match.

    ^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$
    

    This is the raw regex, so you'll need to escape it appropriately for your language. (For example, in some languages you need to double the \ slashes as \\.

    /^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$/
    

提交回复
热议问题