Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for integer or floating point number with two decimals

Tags:

regex

I want to validate my currency field with regex. I want to allow the following pattern entries

1.23
1
.45
0.56
56.00

No comma should be allowed. I've tried \d+(\.\d\d) but it allows only first, fourth and fifth entries. \d+(?:\.\d\d+)? allows all but third one.

like image 961
Krishanu Dey Avatar asked Mar 27 '13 21:03

Krishanu Dey


1 Answers

Use \d* instead of \d+ before the decimal to match zero or more digits. Also add anchors (^ and $) or else it will pass as long as there is any match available. This would also validate an empty string, so if necessary you can use a lookahead to make sure there is at least one digit:

^(?=.*\d)\d*(?:\.\d\d)?$
like image 108
Explosion Pills Avatar answered Oct 18 '22 16:10

Explosion Pills