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

后端 未结 8 1866
情书的邮戳
情书的邮戳 2020-12-11 08:16

I want to validate number in range of 0-255

I have this expression

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

But this a

8条回答
  •  时光说笑
    2020-12-11 08:51

    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.

提交回复
热议问题