Home > Software engineering >  regular expression no more than one digit
regular expression no more than one digit

Time:12-29

how to make a regular expression into one number (only numbers) and that it does not exceed 10 from 0 to 10

/^[1-9][1]*$/.test(message)

It doesn't work that way for me.

CodePudding user response:

To specify the amount of a specific character use {} instead of [], in this case, as it is only one digit, you do not need to specify a count as 1 is default:

/^[0-9]$/.test(message)

I assume you mean you want to match a single digit between 0 and 10. If not please comment to clarify.

Hope this helps.

CodePudding user response:

Assuming you only want integers or whole numbers, then use:

/^(?:[0-9]|10)$/

If you want to allow for decimals, then use:

/^(?:[0-9](?:\.\d )?|10(?:\.0 )?)$/

The second regex says to match:

  • ^ from the start of the number
  • (?:
    • [0-9] 0 to 9
    • (?:\.\d )? any optional decimal component
    • | OR
    • 10 match integer 10
    • (?:\.0 )? optional zero decimal only
  • )
  • $ end of the number
  • Related