Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex with maximum 2 digits after the decimal point

Tags:

regex

I want to write a regular expression that must take a valid only the numerical values with 0, 1 or 2 digits after the decimal point.

So I tried to do it like: "^\\d+(\\.\\d){0,2}$" but it returns true even for numbers with 3 digits after the decimal point.

Any ideas what's wrong?

like image 483
Leo Messi Avatar asked Oct 22 '25 23:10

Leo Messi


1 Answers

Your regex ^\d+(\.\d){0,2}$ matches 1 or 1.0 but also 1.0.0 because you specifiy a quantifier for 0-2 times for the group (\.\d){0,2} and would not match 3 digits after the dot.

To match a digit which could be followed by a dot and 1 or 2 digits after the dot you could use:

^\d+(?:\.\d{1,2})?$

Here the group after the first digit(s) is optional (?:\.\d{1,2})? and the quantifier is specified for the digit \d{1,2}.

like image 116
The fourth bird Avatar answered Oct 26 '25 04:10

The fourth bird