Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to accept only 2 places after

Tags:

c#

regex

Hi all i need all these possible cases to be valid

123
123.1
123.12

I tried this ^[0-9]*\.[0-9]{2}$ or ^[0-9]*\.[0-9][0-9]$ but does not works can any one help me out

like image 626
Vivekh Avatar asked May 12 '11 13:05

Vivekh


2 Answers

Try this:

^[0-9]*(\.[0-9]{1,2})?$

Based on your second example, but allows either one or two decimal places, and makes the whole decimal part optional.

[EDIT]

OP has altered the criteria of the question -- see comments below. He now wants digits prior to the decimal point to only allow up to six digits and has asked me to edit the answer to suit.

All that is needed is to replace the * (for any number of digits) with {0,6} (for between zero and six digits). If you wanted at least one digit, then it would be {1,6}.

Here is the modified regex:

^[0-9]{0,6}(\.[0-9]{1,2})?$
like image 50
Spudley Avatar answered Sep 18 '22 01:09

Spudley


try ...

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

* Edited as suggested to make it non-capturing.

like image 28
Jeff Parker Avatar answered Sep 19 '22 01:09

Jeff Parker