Home > OS >  Regex for input field which accepts percentage with 2 decimals
Regex for input field which accepts percentage with 2 decimals

Time:10-21

Please help me with a regex to validate on a text field to accept. It should accept:

  • 0
  • .50
  • 100
  • 0.01
  • 10.0
  • 99.99

It shouldn't accept:

  • 100.01
  • 50.567

I have an almost working regex with me which accepts unlimited number of decimals, in case it helps:

^(0*100{1,1}\.?((?<=\.)0*)?%?$)|(^0*\d{0,2}\.?((?<=\.)\d*)??)$

CodePudding user response:

This regex could be the one you're looking for:

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

https://regex101.com/r/sLt1g1/1

CodePudding user response:

If you don't want to allow empty strings:

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

The pattern matches:

  • ^ Start of string
  • (?: Non capture group
    • (?:\d{0,2}\.)? Optionally match 0-2 digit and .
    • \d{1,2} Match 1-2 digits
    • | Or
    • 100 Match 100
    • | Or
    • \d{1,2}\. Match 1-2 digits and .
  • ) Close non capture group
  • $ End of string

Regex demo

  • Related