-1

I am trying to write a regular expression which can match enter number string which should be in range of -50 to 100000000

I have tried expression like

^(-?)(1000|[0-9][0-9][0-9]?)$

but it matches only -1000 to 1000 numbers.

example for to test are simple

-50
-39
9
1000
36900
2000022

Please help me to get such expression which can be match range -50 to 100M

I know we can write simple if condition but I want regex only.

Thanks in Advance.

Shree29
  • 634
  • 11
  • 29
  • Are you using pcre or javascript? – Poul Bak Dec 12 '20 at 11:47
  • 5
    That's... not what Regex are for... "I know we can write simple if condition but I want regex only." - WHY?! – Milney Dec 12 '20 at 11:47
  • Related: https://stackoverflow.com/questions/676467/how-to-match-numbers-between-x-and-y-with-regexp – str Dec 12 '20 at 11:50
  • 3
    The minus sign should only be applicable to the -50 till -1 part and not for the whole expression. `^(?:-0*(?:[1-9]|[1-4][0-9]|50)|(?:0*[0-9]{1,8}|100000000))$` – The fourth bird Dec 12 '20 at 11:57

2 Answers2

5

You can use the following regex:

/^(-50|-[1-4]?\d|100000000|[1-9]?\d{1,7})$/gm

Explanation:

^ match start of string

-50 match -50

OR

- only negative numbers

[1-4]? match 1 to 4 - optional, followed by: any number

OR

100000000 match 100000000

OR

[1-9]? match 1 to 9 - optional followed by:

\d{1,7} match any number 1 to 7 times

$ match end of line

Use global and multiline options.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
3

Regular expression serving leading zeros and positive and negative sign. Works only for integers.

^(-0*(50|[0-4]?[0-9])|\+?0*([0-9]{1,8}|100000000))$

Test case

Test case

Using with JavaScript:

let number = -50; /* <-- test number or string here */
let withinTheRange = Boolean(/^(-0*(50|[0-4]?[0-9])|\+?0*([0-9]{1,8}|100000000))$/.exec(number));
Sergio Cabral
  • 6,490
  • 2
  • 35
  • 37