Reputation: 250
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?
Upvotes: 2
Views: 5197
Reputation: 91385
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
Upvotes: 0
Reputation: 10748
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}" );
}
Upvotes: 0
Reputation: 838076
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.
Upvotes: 2