tags:

views:

48

answers:

4

Hi

I'm struggling with a regex problem. The requirement is for decimals to 2 places, non zero and not negative.

Its the non-zero thats getting me.

Anything such as 0.01, 0.99, 99999999.99 is allowed However negative numbers and also 0, 0.0 or 0.00 is not allowed...

I thought I was getting somewhere but this is wrong

^(?!(0)|(0\.0)|(0\.00))[+]?\d+(\.\d|\.\d[0-9])?$

It matches the decimal places and positive numbers fine but I'm attempting to not match if it finds 0, 0.0 or 0.00 but the above looks for a suffix and thats not right as it goes wrong for 0.1, 0.01 etc

Any regex experts out there?

+2  A: 

The error you have made is that you aren't anchoring the lookahead. Your regular expression disallows anything that starts with a zero. Try this instead:

^(?!(?:0|0\.0|0\.00)$)[+]?\d+(\.\d|\.\d[0-9])?$
                    ^
                 anchored

You could simplify \.\d|\.\d[0-9] to \.\d[0-9]?.

I also don't understand why you sometimes use \d and sometimes [0-9]. Be consistent.

Mark Byers
My reason for using \d and then \d[0-9] is that its very late at night, my poor head is fried and I've been playing with a regex builder too long ;). Thanks for the tips, I'll give it a shot at work tomorrow morning
Solyad
Nice one, it works! Thats fantastic...!!
Solyad
A: 
\+?(\d*[1-9]\d*.\d*|0?\.([1-9]\d*|0[1-9]\d*|00[1-9]\d*))
Vadim Shender
A: 

Based on my understanding of your requirements, I like this better than a regex for the whole thing.

C#

public bool IsValid( string number )
{
    return decimal.Parse(number) > 0 && Regex.IsMatch( number, @"\.\d{2}" );
}
BioBuckyBall
A: 

If i understand well your needs, I'll do that :

/^\d+.(\d[1-9]|[1-9]0)$/

This matches any number that have decimal part between 01 and 99

M42
How about 4.00 ;) thats also valid...
Solyad