简体   繁体   中英

How do I match number from 0 to 255 using regex in PHP?

/[0-9]+/ will also match those out of range,like 999

How to write an regex that matches exactly numbers between 0~255 ?

I would do:

$n >= 0 && $n <= 255

Regex are good but they can be avoided in cases like these.

Have a look here :

000..255:       ^([01][0-9][0-9]|2[0-4][0-9]|25[0-5])$ 
0 or 000..255:  ^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$

The simplest solution would be grab the number, convert to an integer and then test that it's value is <= 255. But if you really, really want a regex to do it, then this would work:

^([0-9]{1,2}|1[0-9]{1,2}|2[0-4][0-9]|25[0-5])$

Edit Fixed cause it didn't work in all situations. To be honest, this is why you should just parse the string into an integer and test that the integer value is <= 255.

第一组匹配0-99,第二组100-199,第三组200-249,第四组250-255

/[0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5]/

实际上,你应该匹配0-999然后将值标准化,但......

/(25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([0-9][0-9])|([0-9]))/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM