Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for validating an integer with a maximum length of 10 characters

Tags:

Could you please point me the appropriate RegEx for validating an integer with a maximum length of 10 characters?

Valid ones include: 1234567890

like image 871
OrElse Avatar asked Jan 15 '11 23:01

OrElse


1 Answers

Don't forget that integers can be negative:

^\s*-?[0-9]{1,10}\s*$ 

Here's the meaning of each part:

  • ^: Match must start at beginning of string
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • -: The hyphen-minus character, used to denote a negative integer
    • ?: May or may not occur
  • [0-9]: Any character whose ASCII code (or Unicode code point) is between '0' and '9'
    • {1,10}: Occurring at least one, but not more than ten times
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • $: Match must end at end of string

This ignores leading and trailing whitespace and would be more complex if you consider commas acceptable or if you need to count the minus sign as one of the ten allowed characters.

like image 95
PleaseStand Avatar answered Oct 16 '22 03:10

PleaseStand