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

后端 未结 8 1913
情书的邮戳
情书的邮戳 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 09:07

    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)$
    

提交回复
热议问题