开发者

Regular Expression for number

Please help me to make a Reg开发者_如何学编程ular Expression with following rule -

  1. Max number can be 9999.99
  2. Should be non-negative
  3. Can not be 0, but 0.01 and so on is valid
  4. So, I need a non negative number between 0.01-9999.99


Erm, this isn't really a job for Regexp, but it works with it anyway:

/(\d{2,4}(\.(\d[1-9])|([1-9]\d))?)|[1-9]/

A More strict evaluation would be:

/^([1-9]\d{,3}(\.\d{1,2})?)?|(0\.([1-9]\d?)|(0\.0[1-9]))$/

With not accepting leading zero's, but allowing for just one decimal: "0.1". Bear in mind, decimals are optional.

I suggest, however, to use mathematical operations: Convert to float and then check:

if((num > 0) && (num < 100000)) {...}

You can use sprintf() to get the representation that you need, for instance limiting the number of decimals, etc.


Why do you need a regular expression to do this? Just convert your string to a double and check if it's between 0.01 and 9999.99.


As people have already answered, you can get digits fairly easily by using [0-9] or \d. By using {min,max} you can specify how many of a character or character set to get for a match.

Here's a good reference: http://www.regular-expressions.info/reference.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜