what am I missing in this RegEx?
I'm trying to create a JavaScript Regex to test for:
a valid # between 0 and 99.9 (where only a single decimal digit is allowed) e.g. 3.45 is not valid.
so, blank is ok, any integer between 0 and 99 is ok, and a decimal value is allowed.
开发者_高级运维I have this so far, but it is allowing values like 3.45
to pass:
$^|$[0-9][0-9]?^|$[0-9][0-9]?.[0-9]^
Two problems I can see:
- You mixed up ^ and $.
- Your decimal point needs escaping
\.
.
Mark already said what is wrong with your expression. Here is another way how you could write it:
^(\d\d?(\.\d)?)?$
Explanation:
^
matches the beginning of the string(...)?
makes the whole number optional$
matches the end of the string\d\d?
matches either one or two digits (?
makes the second one optional)(\.\d)?
matches a dot.
and a digit (?
makes it optional)
I've never really used much JavaScript, but this should do the job...
^[0-9][0-9]?(?:\.[0-9])?$
Rewrite your regex as :
^$|^[0-9][0-9]?$|^[0-9][0-9]?\.[0-9]$
But better, use Felix King's one.
Another variant is
/^\d{0,2}(\.\d)?$/
which will accept numbers like .3 if such are to be allowed.
精彩评论