Arthur Frankel
Arthur Frankel

Reputation: 4705

regular expression to match -100 to 0

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

So valid values are:

Invalid are:

Thank you!

Upvotes: 2

Views: 798

Answers (5)

Matteo Riva
Matteo Riva

Reputation: 25060

Use this function:

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

Upvotes: 8

Randy the Dev
Randy the Dev

Reputation: 26710

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

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

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"?

Upvotes: 2

Saurabh Kumar
Saurabh Kumar

Reputation: 2367

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

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

Upvotes: 0

Christopher Hunt
Christopher Hunt

Reputation: 2081

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?

Upvotes: 0

Related Questions