tags:

views:

159

answers:

6

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

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

+3  A: 

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])$
tanascius
+2  A: 
Dean Harding
That does **not** match 150 to 199 btw
S.Mark
S.Mark: Updated my answer, thanks :)
Dean Harding
+1  A: 

In reality, you should just match 0-999 and normalise the values afterwards, but...

/(25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([0-9][0-9])|([0-9]))/
Delan Azabani
Or just catch any integer with /(\d+)/
Steve-o
+12  A: 

I would do:

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

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

codaddict
best answer so far
stereofrog
+2  A: 

first group matches 0-99, second one 100-199, third 200-249, fourth 250-255

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

first group matches 0-99, second one 100-199, third 200-249, fourth 250-255

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