regex For Float Numbers with Limits

916 Views Asked by At

I need regex Expression for Floating and whole numbers that have the limit like it will accept 1 or 2 digit before point and 1 or 2 digits after point. Whole number limit should be 2 digit. What should be valid:

 - 1.1
 - 11.1
 - 1.11
 - 11.11
 - 2
 - 22

What should be invalid:

 - 111.111
 - 222
Here is my Regex:
/^\d{1,2}(\.\d){1,2}?$/


But it is not working properly
kindly help me in this
2

There are 2 best solutions below

2
sniperd On

Try this:

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

Making the 2nd part of the regex optional

4
Wiktor Stribiżew On

Use the following pattern:

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

See the regex demo.

enter image description here

Details:

  • ^ - start of string
  • \d{1,2} - 1 or 2 digits
  • (?:\.\d{1,2})? - an optional sequence of:
    • \. - a dot
    • \d{1,2} - 1 or 2 digits
  • $ - end of string.