1

I'm trying to find the most succinct way to write a regular expression for integers from 0-100 inclusive. This is what I have so far, is there a better form?

^[0-9][0-9]?$|^100$
MattDionis
  • 3,534
  • 10
  • 51
  • 105
  • 1
    possible duplicate of [Using regular expressions to validate a numeric range](http://stackoverflow.com/questions/22130429/using-regular-expressions-to-validate-a-numeric-range) – AD7six Sep 01 '15 at 16:55
  • 1
    Note your regex allows `00` but not `000`. – Oriol Sep 01 '15 at 16:58

3 Answers3

1

Regex is a very powerful tool for certain tasks, but it can quickly get out of hand when applied to things it's not designed for. It's hard to say without knowing why you need this particular regex, but in most cases I would prefer capturing the number you want and then using your programming language to evaluate whether the captured value is in the desired range. This just seems like a case where regex is going to needlessly complicate your code.

That said, if you're committed to using a regex and don't want leading zeros, you probably want ^[1-9]?\d$|^100$.

agrasley
  • 68
  • 4
1

I'd recommend against doing this, but to answer your question...I'd argue that this regular expression is the most succinct/pure version:

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

Demo


Notes

  • I used a (non-capturing) group so the ^ and $ anchors only are used once.
  • I put 100 first in the alternation since 99% (arbitrary estimation) of the time it will be more efficient...200 will fail right away rather than matching 20 and then failing.
  • I elected to not use \d, since it isn't the same as [0-9].
Community
  • 1
  • 1
Sam
  • 20,096
  • 2
  • 45
  • 71
0

Handling every case,like 001 or 00001, makes it more complex, this is the best I can think of. For sure you can use \d to make it look shorter.

^0*\(100\|^[0-9]\?[0-9]\)$
perreal
  • 94,503
  • 21
  • 155
  • 181