开发者

What regex can I use to validate a number between 0 and 255?

开发者 https://www.devze.com 2023-03-16 18:50 出处:网络
I want to validate number in ran开发者_如何学Goge of 0-255 I have this expression \'/^([0-1]?[0-9]?[0-9])|([2][0-4][0-9])|(25[0-5])$/\'

I want to validate number in ran开发者_如何学Goge of 0-255

I have this expression

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

But this accepts any number... And this works:

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

why do I have to have ^ and $ for each option?

edit: I have it, but I cannot answer my question, so - ^ and $ have higher priority than |, so /^(...)$/ helped


Note: @alex's answer is the way to go. Validating a number range with regex is like using a jackhammer to catch a fly.

But nevertheless I wanted to provide an explanation for this "problem".


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

'/^(([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$)

With the brackets, it will be

^(number OR number OR number)$


Don't use a regex for validating a number range.

Just use a condition...

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

This will ensure the number is between 0 and 255 inclusively, which is what your regex appears to be doing.

To answer your question specifically, it doesn't work because you need to wrap the whole thing with a capturing group otherwise the regex engine will do an 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 the string.


one more method (but previous solution is better I think)

in_array($number, range(0, 255))


I played with it further, and here is regex for strict 0-255 range, without leading zeroes permitted:

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


First off, I agree that @Alex's answer is the way to go if available; however, it may be worth mentioning that the regex version can be done with the somewhat more concise pattern:

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

...which is what I use when numeric parsing isn't an option.


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

will work


^(([0-9]|[1-9][0-9])|[1][0-9][0-9]|[2][0-5][0-5])$ this works for 0-255 meaning no leading zeros such as 001


I know this has been answered, but I needed a similar regex for page routing; except for the range of 1-66. This worked well: /^(?!67|68|69)[1-6][0-9]|[1-9]$/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号