1

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Fizzah
  • 63
  • 1
  • 2
  • 12

2 Answers2

2

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Wow, I like that slick graphic – sniperd Jul 25 '17 at 12:47
  • Thank you so much. It is working perfectly. Can u Explain an optional sequence. \d{1,2} this is for the digit, \. this is for point , \d{1,2} this is for digit after point. but ?: what is this. How it is working in the expression – Fizzah Jul 26 '17 at 05:23
  • @Fizzah `(?:...)` is a [**non-capturing group**](https://stackoverflow.com/a/3513858/3832970). It is used to only group patterns without storing the value captured in a memory buffer. What makes it optional is the `?` quantifier after it. The `?` makes the whole pattern inside the non-capturing group be matched 1 or 0 times. – Wiktor Stribiżew Jul 26 '17 at 06:17
  • Got it. Thank You so much – Fizzah Jul 26 '17 at 06:25
0

Try this:

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

Making the 2nd part of the regex optional

sniperd
  • 5,124
  • 6
  • 28
  • 44
  • Yeah, after a fix as per my comment above it will work, but there is no need using a capturing group, a non-capturing is enough. Now, our solutions are almost identical. – Wiktor Stribiżew Jul 25 '17 at 12:48
  • @WiktorStribiżew Your answer is much better, where did you make that graphic from? – sniperd Jul 25 '17 at 12:50