What regular expression can be used to check a number from 0 to 255?

I want to check a number in the range 0-255

I have this expression

'/^([0-1]?[0-9]?[0-9])|([2][0-4][0-9])|(25[0-5])$/' 

But it takes any number ... And it works:

 '/(^[0-1]?[0-9]?[0-9]$)|(^[2][0-4][0-9]$)|(^25[0-5]$)/' 

why do i need to have ^ and $ for each option?

edit: I have this, but I can not answer my question, so - ^ and $ have a higher priority than | , so /^(...)$/ helped

+4
source share
8 answers

Note: @alex answer is the way to go. Checking a range of regular expression numbers is like using a jackhammer to catch a fly.

Nevertheless, I wanted to give an explanation of this "problem".


You don't have to, you just need to group it correctly, which means you need to group the rotation:

 '/^(([0-1]?[0-9]?[0-9])|([2][0-4][0-9])|(25[0-5]))$/' // ^ ^ 

Otherwise, the expression will be interpreted as follows (logically)

 (^number) OR (number) OR (number$) 

In brackets will be

 ^(number OR number OR number)$ 
+7
source

Do not use regex to test a range of numbers.

Just use the condition ...

 if ($number >= 0 AND $number <= 255) { ... } 

This ensures that the number is between 0 and 255 inclusive, which is what your regular expression does.

To answer your question specifically, it does not work, because you need to wrap it all with a capture group, otherwise the regex engine will do the OR of each individual regex ...

 /^([0-1]?[0-9]?[0-9]|[2][0-4][0-9]|25[0-5])$/ 

Also note that $ will match before any trailing \n . Use \z if you really want to match at the end of a line.

+6
source

another method (but the previous solution is better, I think)

 in_array($number, range(0, 255)) 
+2
source

I played with him further, and here is a regular expression for a strict range of 0-255, without valid zeros:

'/^([0]|[1-9]\d?|[1]\d{2}|2([0-4]\d|5[0-5]))$/'

+2
source

First, I agree that the @Alex answer is the way to go, if available; however, it may be worth mentioning that the regular expression version can be executed with a slightly shorter template:

 /^([01]?\d{1,2}|2([0-4]\d|5[0-5]))$/ 

... this is what I use when numerical parsing is not an option.

+1
source

[0-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0-9] | 25 [0-5]

will work

0
source

^(([0-9]|[1-9][0-9])|[1][0-9][0-9]|[2][0-5][0-5])$ this works for 0-255, which means no leading zeros like 001

0
source

I know this was answered, but I needed a similar regular expression to route the page; excluding the range 1-66. This works well: / ^ (?! 67 | 68 | 69) [1-6] [0-9] | [1-9] $ /

0
source

Source: https://habr.com/ru/post/925215/


All Articles