Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

0.01 to 99.99 in a regular expression

Tags:

regex

php

I'm trying to do a regular expression that'll allow numbers from 0.01 to 99.99, but not 0.0 or any null value (00.00 or 00.0 or 0.00 or 0.0) or negative value either. I've come quite close, but as usual something just isn't right. 0.0 shows as valid. Can you please help me fix this. Also, you don't need to keep the expression I've done :)

<?php
if (preg_match('/^[0-9]{1,2}[\.][0-9]{1,2}$/','0.0'))
{echo "Valid";}else{echo "Invalid";}
?>
like image 894
Norman Avatar asked Oct 16 '25 07:10

Norman


2 Answers

Here's my attempt:

/^(?=.*[1-9])\d{0,2}(?:\.\d{0,2})?$/

First off, use a positive look-ahead ((?=.*[1-9])) to ensure that there is at least one "significant digit" in the whole mess, will fail for all forms of 0.0, 00.00 or whatever. The next part \d{0,2} allows 0, 1, or 2 digits before the decimal point, then an optional group (?:)? that includes a literal decimal, followed by 0, 1 or 2 digits: \.\d{0,2}. Use the ^ and $ to make this expression complete by only matching from beginning to end of string.

Some quick test strings:

0.0 failed.
0 failed.
12 matched.
123 failed.
05.00 matched.
0.01 matched.
like image 114
gnarf Avatar answered Oct 18 '25 22:10

gnarf


Why not

<?php
$value = '0.0';
if ($value > 0 && preg_match('/^[0-9]{1,2}[\.][0-9]{1,2}$/', $value)) {
   echo "Valid";
} else {
   echo "Invalid";
}

Sometimes a regex is not a solution, but rather a problem ;-).

like image 44
Dan Soap Avatar answered Oct 18 '25 20:10

Dan Soap