I am having a bit of difficulty with the following:
I need to allow any positive numeric value up to four decimal places. Here are some examples.
Allowed:
123
12345.4
1212.56
8778787.567
123.5678
Not allowed:
-1
12.12345
-12.1234
I have tried the following:
^[0-9]{0,2}(\.[0-9]{1,4})?$|^(100)(\.[0]{1,4})?$
However this doesn't seem to work, e.g. 1000 is not allowed when it should be.
Any ideas would be greatly appreciated.
Thanks
This regex would do the trick:
From the beginning of the string search for one or more digits. If there's a
.
it must be followed with atleast one digit but a maximum of 4.To explain why your attempt is not working for a value of
1000
, I'll break down the expression a little:There is no room for 4 digits of any sort, much less
1000
(theres only room for a 0-2 digit number or the number 100)This expression will pass any of the allowed examples and reject all of the Not Allowed examples as well, because you (and I) use the beginning-of-string assertion
^
.It will also pass these numbers:
... as well as a completely blank line - which might or might not be desired
to make it reject something that starts with a zero, use this:
This expression (which uses a negative lookahead) has these evaluations:
You could also test for a completely blank line in other ways, but if you wanted to reject it with the regex, use this:
The will match something with doesn't start with -, maybe has a + followed by an integer part with at least one number and an optional floating part of maximum 4 numbers.
Note: Regex does not support scientific notation. If you want that too let me know in a comment.
If you have a double value but it goes to more decimal format and you want to shorter it to 4 then !
Try this:
Explanation: match only if starting with a digit (excluding negative numbers), optionally followed by (non-capturing group) a dot and 0-4 digits.
Edit: With this pattern
.2134
would also be matched. To only allow 0 < x < 1 of format0.2134
, replace the first*
with a+
above.