Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

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

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

like image 453
user198729 Avatar asked May 06 '10 07:05

user198729


5 Answers

I would do:

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

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

like image 177
codaddict Avatar answered Oct 18 '22 20:10

codaddict


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])$
like image 39
tanascius Avatar answered Oct 18 '22 18:10

tanascius


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.

like image 31
Dean Harding Avatar answered Oct 18 '22 19:10

Dean Harding


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]/
like image 39
brian_d Avatar answered Oct 18 '22 19:10

brian_d


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]))/
like image 26
Delan Azabani Avatar answered Oct 18 '22 19:10

Delan Azabani