sameer sameer - 1 month ago 19
C# Question

Regex restricting 2 decimal places

I am sorry,this question will be marked previously asked.But I went through many threads.There are many answers to the given problem.But some how i am unable to figure out what i am doing wrong.
My requirement is to not match more than 1 numeric after decimal
and Also non decimal numbers should be discarded.
eg

Valid

1.1

12.1

1234.1

123456.0

Invalid

.12

123

123.12

What i wrote
^([0-9]?.?)+.?[0-9]{1}$

When i try to match 11.123 or 123 i get a match. What am i doing wrong?

Answer

This regex works for your use case: ^\d+\.\d$
WHere ^\d+ match from starting of the string all digits (that must be one or more since there is +), then escape . with \. and finally \d$ match only if there is one char before the end of the string

Comments