我可以使用什么正则表达式来验证0到255之间的数字? [英] What regex can I use to validate a number between 0 and 255?
问题描述
我想验证0-255之间的数字
I want to validate number in range of 0-255
我有这个表情
'/^([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$)
带有括号的将是
^(number OR number OR number)$
这篇关于我可以使用什么正则表达式来验证0到255之间的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!