Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for Decimals

Tags:

html

jquery

regex

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.

like image 230
Cody Harness Avatar asked Jan 25 '26 17:01

Cody Harness


2 Answers

/^\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

like image 71
Richard Hamilton Avatar answered Jan 28 '26 06:01

Richard Hamilton


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.

like image 36
anubhava Avatar answered Jan 28 '26 07:01

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!