How can i change this regular expression
/^[1-9][0-9]{0,3}$|^[1-9][0-9]{0,3}[\.][0-9]$/
to see 开发者_如何学编程that it accepts "0.1" and "0.2" and so on values but it should not accept "0.0"
one to four digits, with or without decimal precision of 1:
/^[1-9][0-9]{0,3}(\.[0-9])?$/
0.1 through 0.9, step 0.1:
/^0\.[1-9]$/
/^[1-9][0-9]{0,3}(\.[0-9])?$|^0\.[1-9]$/
This really doesn't sound like a regex problem: you'd be much better off (from a maintainability and readability standpoint) treating your numbers as numbers and doing a simple range check:
var isValid = function (x) {
// Make sure we're dealing with a number
x = parseFloat(x);
// If x is greater than zero but less than 0.9
// this expression evaluates to true so the
// function returns true, otherwise it evaluates
// to false so the function returns false.
return (x > 0 && x <= 0.9);
};
Sure, it doesn't use any regexes (which is what you were asking for) but there's no good reason to use them to solve this problem (mostly because it is much more easily solved using the above method)
RegExp covering existing cases, but also allowing decimals 0.1 <= n <= 0.9
.
/^[1-9][0-9]{0,3}$|^[1-9][0-9]{0,3}\.[0-9]$|^0\.[1-9]$/
or better, from Dreynold's solution:
/^[1-9][0-9]{0,3}(\.[0-9])?$|^0\.[1-9]$/
Old Answer, for reference, requirements updated by OP:
If you only want a single decimal place, with the existing allowed values:
/^[1-9][0-9]{0,3}$|^[1-9][0-9]{0,3}[\.][0-9]$|^0\.[1-9]$/
If just the decimal then:
/^0\.[1-9]$/
If multiple decimals then:
/^[1-9][0-9]{0,3}$|^[1-9][0-9]{0,3}[\.][0-9]$|^0\.[1-9][0-9]*$/
or
/^0\.[1-9][0-9]*$/
精彩评论