Home > Mobile >  simple regex to allow numbers from -20 to 20 with decimal points
simple regex to allow numbers from -20 to 20 with decimal points

Time:05-13

how can I specify a regex that allows numbers from -20 to 20, including 0 and decimal points?

e.g all of the following are allowed:

20 19.99 5 0.5 0 1 3.45 -20 -17.20

CodePudding user response:

If you're looking for a regex for your task, you can use this one:

^-?1?\d(\.[\d] )?$|^-?20$

Explanation:

  • ^: start of number
  • -?: optional minus
  • 1?: optional 1 for tens
  • \d: any digit for units
  • (\.[\d] )?: optional decimal places with any digit
  • $: end of number

or

  • ^: start of number
  • -?: optional minus
  • 20: 20
  • $: end of number
  • Related