tags:

views:

85

answers:

4

Hi. Please help me to make a Regular 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
+2  A: 

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.

BoltClock
A: 

A Perl-compatible regex would be ^\d{1,4}\.\d{2}$

Blagovest Buyukliev
This accepts `0000.00`, though.
eldarerathis
wrong: it matches `0.00` which he didn't want. Also it doesn't match `1` to `9999`
polemon
`{1,4}` is greedy. So yes, it does match `0000.00`. See: http://www.regular-expressions.info/reference.html
eldarerathis
+3  A: 

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.

polemon
+1 for making the period and decimal part optional -- the OP didn't specify it, but without that, an input like "100" would fail. +1 for saying Regex is the wrong tool for parsing numbers!
Val
Hi, Thanks for your answer. I need a regular expression because number should have maximum two digits after decimal. So, 9.9999 is invalid though it is in between 0-10000
Saurabh
Also, the expression you have given is not working as expected.
Saurabh
It's PCRE, you need to tailor it to your Regexp-Dialekt.
polemon
I converted this to ^(\d{2,4}(\.(\d[1-9])|([1-9]\d))?)|[1-9]$But its allowing multiple zero.
Saurabh
I agree that numerical comparisons are the best way to handle this, but the regex you gave is really not correct. The last alternative (`[0-9]`) will match *any* string with a digit in it because you didn't anchor it. If you do anchor this regex, it won't match single digit floats (eg: `1.9`) which the OP wants to accept.
eldarerathis
I did, some changes to the answer. In case you need a more specific match, restate your question.
polemon
A: 

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

Lunin