I have a simple expression that I need to write, but I'm really not that great with regex.
My limits are: maximum 1 digit . maximum 4 digits, allowing less
These should pass.
1
1.2
1.23
1.234
1.2345
These should fail.
10
10.1
1.23456
The closest I've come is \d\.\d{0,4}, but it doesn't select 1, and selects the 0.1 and 1.2345 from the second list.
I should also specify that this is a check being done as the user types, if that makes a difference.
Edit
Since there are so many responses that cover several different points, I feel I should specify some more, especially because someone might point me down a better path. I am using this on a web form. It needs to only allow these conditions as the user types, so if they have "4" and try to enter "1" it won't allow it, but will if they enter "." first. Or will not allow input after they do something like "2.5345", since that's 4 digits after the decimal.
/^\d(\.\d{0,4})?$/
RegEx breakdown
/ - Indicates the start of a Regular Expression
^\d - The expression starts with a digit
\. - Periods need to be escaped because otherwise they match any character.
\d{0,4} - Will match between 0 and 4 digits.
() - Captures everything enclosed
? - Matches 0 or 1 of an expression
You can use this regex:
^\d(\.\d{0,4})?$
RegEx Demo
(\.\d{0,4})? makes part after decimal optional to allow for single digits as valid input.
Caveat: This will also allow 9. as valid input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With