开发者

Preventing Multiple Decimal Points

I'm not a computer science person and I'm trying to figure out how to prevent a user from entering in more than one decimal point. For example, how d开发者_JAVA百科o I stop someone from entering 3..5?


The background given in the question is practically non-existent, but the proper way to do this would be try to parse the input with whatever language you are using, and if it fails, reject it. But if you want a regex:

^\d+\.\d+$    # allows numbers with a single decimal point; 
                fails if it doesn't have one
^\d+(\.\d+)?$ # allows numbers with a decimal point or without one

Note these regexes allow an unlimited number of digits on either side of the decimal point. If you want to specify the number of digits, you can use {m...n} instead of the + quantifier:

^\d{1,3}\.\d{1,3}$   # allows numbers from 0.0 to 999.999

EDIT: If you want to allow input of the form .25 like tchrist suggests, you could use :

^\d*\.\d+?$ 


For a floating-point number, ie ###.##, you can match

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

This will allow any number of digits, followed by a single decimal (required) followed by one or 2 digits.


Try this:

m{
    ^ (?: \. \d{1,2}   # eg: ".25"
        | \d+          # eg: "2343409823409823049823094823094820389402984230948"
              (?:
                  \. \d{0,2}
              )?       #  eg: "186282.42"
      ) 
    $
}x
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜