tags:

views:

126

answers:

5

I need a regular expression to match all numbers inclusive between -100 and 0.

So valid values are:

  • 0
  • -100
  • -40

Invalid are:

  • 1
  • 100
  • 40

Thank you!

+7  A: 
/^(?:0|-100|-[1-9]\d?)$/
kemp
**This is wrong.** You need to group the alternation to prevent the `^` and `$` markers from being included with the first and last options. i.e. `^(?:0|-100|-\d\d?)$`
Peter Boughton
Also, as commented by Aaron on the question, this will currently match -0 and -04. Need to use `[1-9]` in place of the first `\d` to avoid that.
Peter Boughton
You're very right peter, updated my answer with your corrections
kemp
A: 

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

But perhaps it would be simpled to cast it to numeric and quickly check the range then

Saurabh Kumar
A: 

How about using a capture group and then programmatically testing the value e.g.

(-?\p{Digit}{1,3})

and then testing the captured value to ensure that it is within your range?

Christopher Hunt
Depending on how the match is done, this might also match `-99` within `-999`, so to be safe, better surround this by anchors. Otherwise that's probably what I would do.
Tim Pietzcker
+2  A: 

OK, so I'm late, but here goes:

(?:         # Either match:
 -          # a minus sign, followed by
 (?:        # either...    
  100       # 100
  |         # or
  [1-9]\d?  # a number between 1 and 99
 )
 |          # or...
 (?<!-)     # (unless preceded by a minus sign)
 \b0        # the number 0 on its own
)
\b          # and make sure that the number ends here.
(?!\.)      # except in a decimal dot.

This will find negative integer numbers (-100 to -1) and 0 in normal text. No leading zeroes allowed.

If you already have the number isolated, then

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

is enough if you don't want to allow leading zeroes or -0.

If you don't care about leading zeroes or -0, then use

^-?0*(?:100|\d\d?)$

...Now what do you do if your boss tells you "Oh, by the way, from tomorrow on, we need to allow values between -184.78 and 33.53"?

Tim Pietzcker
upvoted for the detailed comments. Uncommented regex are a pain to deal with.
Tim
A: 

I'm new to regular expressions would this work? (-100|((-[1-9]?[0-9])|\b0))

Andrew Dunn