dskld5423 2011-07-02 22:51
浏览 1099
已采纳

我可以使用什么正则表达式来验证0到255之间的数字?

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

  • 写回答

8条回答 默认 最新

  • drqxfmfa804578 2011-07-02 22:57
    关注

    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)$
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器