0

I am trying to build a regex for user input that will handle both: integers and floats in the range of 0 to 999.99. Acceptable values are: 0, 0.00, 10, 10.41, 150, 150.53... etc. The small catch is that the amount of preceding and trailing zeroes should be unlimited, so it would accept 0000153 as well as 153.0000000.

I have managed to build a very similar one, for handling values between 100 to 9999.99 - works perfectly.

(0*(?=[1-9])[1-9]?[0-9]{3}?(\.\d{1})?(\d{1}0*)?)

I've been trying to remodel it, but there is always something wrong with it.

Thank you for your help.

  • `^0*(?:[0-9]|[1-9][0-9]{1,2})(?:\.\d+)?$`, right? Use the [numeric range regex generator](https://stackoverflow.com/a/67502416/3832970), with 3 options checked: 1) Match whole string, 2) Allow leading zeros, 3) Optionally match fractional digits (floats) – Wiktor Stribiżew Oct 24 '22 at 08:28
  • @WiktorStribiżew When checking it in https://regexr.com/ this alteration is almost perfect, however it allows for an infinite number of digits after the floating point, and I have no clue why :) Thank you for your help! – mariaILikeIt Oct 24 '22 at 08:36
  • Can't you just use `^0*\d{1,4}(?:\.\d{1,2}0*)?$`? This would mean that only the first two decimal digits could be different to 0. The 1-4 digits will allow for leading zeros and a potential max value of 9999. – JvdV Oct 24 '22 at 08:37
  • 1
    @WiktorStribiżew we have a winner, thank you so much. I am saving the resource with the numeric range regex gen to my favs. Have a good day :) JvdV - Very elegant solution, however it passes numbers such as 000000000000001000000, that would be 1 000 000 after removal of the leading zeroes and it's out of range. – mariaILikeIt Oct 24 '22 at 08:39
  • @mariaILikeIt, it won't nomore. I accidentaly had the trailing zero's outside the optional non-capture group. Please test again. – JvdV Oct 24 '22 at 08:51
  • @JvdV thank you - it seems to pass all of the test values I prepared. I will check it with our testers. – mariaILikeIt Oct 24 '22 at 09:16

0 Answers0