1

my current regex:

/^[0-9]{3}$/

This will match if the value is an integer with a length of 2.

I need to expand this a bit further by matching only values between 0 - 32.

0 <- not match
1 <- match
2 <- match
...
29 <- match
30 <- match
32 <- not match
33 <- not match

Test your regex: https://regex101.com/

dawg
  • 98,345
  • 23
  • 131
  • 206

2 Answers2

2

This works:

/^((?:[1-9])|(?:[1-2][0-9])|(?:3[0-1]))$/

Test it in Python:

for i in range(0,321):
    m=re.match(r'^((?:[1-9])|(?:[1-2][0-9])|(?:3[0-1]))$', str(i))
    if m:
        print i
# prints 1-31...

Test in Bash / Perl:

$ echo {0..3500} | tr ' ' '\n' | perl -nle 'print $1 if /^((?:[1-9])|(?:[1-2][0-9])|(?:3[0-1]))$/'
prints 1-31

And test in regex101

dawg
  • 98,345
  • 23
  • 131
  • 206
0

Required regex can be formed like this

/^[1-9]$|^[1-2][0-9]$|^3[0-2]$/

Also, the given regex will match only 3 digit integers.

Vikas Bansal
  • 147
  • 6
  • Seems like OP wants a regex to match 0 - 32, not a 3 digit integer.. – Jonas Czech Apr 04 '15 at 16:23
  • Can you break the regex apart and describe what is happening? i need to be able to use this same statement for another number. I'm starting to think i cant do what im trying to do. –  Apr 04 '15 at 16:24
  • There are three parts in this regex. `^[1-9]$` matches any number between 1-9. `^[1-2][0-9]$` matces a number between 10 and 29. `^3[0-2]$` will match an integer between 30 and 32. You can try them separately. @JonasCz by "given regex" i meant the regex which is mentioned in the question. – Vikas Bansal Apr 04 '15 at 16:33