0

How to write regular expression which accept numbers between 1 to 25000>

I tried like this ^([1-2]?[1-4]?[0-9]{0,3}|25000)$

dBz
  • 49
  • 8
  • You will get this and more at http://gamon.webfactional.com/regexnumericrangegenerator/ – Wiktor Stribiżew Jul 22 '18 at 10:13
  • try this pattern \b([0-9]|[1-8][0-9]|9[0-9]|[1-8][0-9]{2}|9[0-8][0-9]|99[0-9]|[1-8][0-9]{3}|9[0-8][0-9]{2}|99[0-8][0-9]|999[0-9]|1[0-9]{4}|2[0-4][0-9]{3}|25000)\b – Husam Ebish Jul 22 '18 at 10:52

2 Answers2

1

Here's a regex that will only accept a string with a number between 1 and 25000.
Without proceeding zero's.

^([1-9]\d{0,3}|1\d{4}|2[0-4]\d{3}|25000)$

It basically separates it in 4 ranges

[1-9]\d{0,3} : 1 to 9999  
1\d{4}       : 10000 to 19999  
2[0-4]\d{3}  : 20000 to 24999  
25000        : 25000  

A regex101 test can be found here

To find those numbers as a part of a string, you could replace the start ^ and end $ by a wordboundary \b.

Btw, in most programming languages it's often simpler to just check if it's a number that's in the accepted range. Even in HTML there's an input type for numbers where you can set the minimum and maximum.

LukStorms
  • 28,916
  • 5
  • 31
  • 45
0

Try

^(?!0$)((1\d|2[0-4]|\d)?\d{1,3}|25000)$

First negative lookahead will reject a value of only 0.

The group (1\d|2[1-4]|\d)? means that a 5-digit number with an initial digit of 2 requires it to be followed by a 0-4.

https://regex101.com/r/1DgbBM/4

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320