Home > database >  Regex for percentage with 2 decimal places
Regex for percentage with 2 decimal places

Time:12-22

I am looking to build 2 regex with those constraints :

  • 0 to 100
  • 2 decimals places (like 15.25 or 0.01)
  • But 100.01 is not acceptable
  • No negative number

For the second regex, I need it to go up to 200 instead of 100 but same for the rest.

Currently, I have this one for 0 to 100 :

^([0-9]|[1-9][0-9]|100)?$

and this one for 200

^([01]?[0-9][0-9]?|200)?$

I can get 0 to 100 or 200 numbers but without decimal places.

CodePudding user response:

First regex: /^([0-9]{1,2}|[0-9]{1,2}\.[0-9]{2}|100)?$/

regex101.com

CodePudding user response:

You can extend your regex like this:

^([0-9]|[1-9][0-9]|(?:[0-9]|[1-9][0-9])\.(?:[0-9]|[0-9][0-9])|100)?$

You can try it here: https://regex101.com/r/HBidWk/1

This is for 0-100

  • Related