问题
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";}
?>
回答1:
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.
回答2:
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 ;-).
回答3:
Are you sure you need to do it in a regular expression?
If you are using a regex because you are trying to evaluate a string, you can always cast it as a double first and then do a simple numeric comparison.
<?php
function test_number($number)
{
$number = (double) $number;
if ($number >= 0.01 && $number <= 99.99) {
return true;
} else {
return false;
}
}
回答4:
Try this regular expression:
/^(?:0\.(?:0[1-9]|[1-9]\d)|[1-9]\d?\.\d\d)$/
回答5:
A simple solution:
<?php
function test($n) {
return($n > 0.0 and $n < 99.99);
}
echo test(85); //output 1(true)
?>
回答6:
I asume you consider only 1 or 2 digit followed by a point followed by 2 decimals
Two solutions:
1) Do a DFA than translate that to regex
0\.0[1-9] | 0\.[1-9][0-9] | [1-9][0-9]?\.[0-9][0-9]
OR
2) accept any 1-2 digit(s), 2 decimal:
[0-9][0-9]?\.[0-9][0-9]
and then test:
0 < num && num < 100
:-)
来源:https://stackoverflow.com/questions/3727052/0-01-to-99-99-in-a-regular-expression