Link to home
Start Free TrialLog in
Avatar of x95guzik
x95guzikFlag for United States of America

asked on

regex IP validator

Below is a regex for validating an ip address.  I need to modify it to accept a x instead of numbers at any point in the entry.

Example:
want it to accept 222.123.213.54 and also accept 222.123.x.54 ect where the x can replace any one set of numbers.  Thanks in advance and more power to the folks who understand regex as it is like a foreign language to me.

"^((?:([2]{1}[0-5]{2})|([2]{1}[0-4]{1}[0-9]{1})|([1]?[0-9]{2})|([0-9]{1}))[\\.]){3}(?:([2]{1}[0-5]{2})|([2]{1}[0-4]{1}[0-9]{1})|([1]?[0-9]{2})|([0-9]{1}))(\\:[0-9]{1,5})?$"
Avatar of star_trek
star_trek

"^((?:([2]{1}[0-5]{2})|([2]{1}[0-4]{1}[0-9]{1})|([1]?[0-9]{2})|([0-9]{1}))[\\.]){2}((?:([2]{1}[0-5]{2})|([2]{1}[0-4]{1}[0-9]{1})|([1]?[0-9]{2})|([0-9]{1})|(x))[\\.]){1}(?:([2]{1}[0-5]{2})|([2]{1}[0-4]{1}[0-9]{1})|([1]?[0-9]{2})|([0-9]{1}))(\\:[0-9]{1,5})?$"
Avatar of Roonaan
if(preg_match('/^222\.123\.\d{1,3}\.54$/', $myIPString)) {
  //valid
} else {
  //invalid.
}

-r-
Avatar of x95guzik

ASKER

thanks star_trek  One last thing is that I want x to substituable for any of the last three.  I am trying figure it out form what you sent but am still fighting through.
If I understand properly,  then here is the following "^((?:([2]{1}[0-5]{2})|([2]{1}[0-4]{1}[0-9]{1})|([1]?[0-9]{2})|([0-9]{1}))[\\.]){2}((?:([2]{1}[0-5]{2})|([2]{1}[0-4]{1}[0-9]{1})|([1]?[0-9]{2})|([0-9]{1})|(x))[\\.]){1}(?:([2]{1}[0-5]{2})|([2]{1}[0-4]{1}[0-9]{1})|([1]?[0-9]{2})|([0-9]{1})|(x))(\\:[0-9]{1,5})?$"
Can you give an example of what exactly you want, in above i substituted x for the fourth string after the dot
222.123.213.54  or 222.123.x.54 or 222.123.x.x or 222.123.213.x

let me know if that is waht you wanted from your request.
192.x.12.12 - 192.12.x.12 - 192.12.12.x - 192.x.x.12 - 192.12.x.x would all be valid.
and if it is easier no problems with 192.x.x.x would be ok to.  So basically all can be x except the first one
ASKER CERTIFIED SOLUTION
Avatar of star_trek
star_trek

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can do this without regexp:

<?php

function matchPattern($pattern, $ip) {
  $parts1 = explode('.', $pattern);
  $parts2 = explode('.', $ip);
  foreach($parts1 as $index => $key) {
     if($parts2[$index] != $key && $key != 'x') return false;
  }
  return true;
}

if(matchPattern('192.x.x.x', '192.1.2.3')) {
  echo 'matches';
} else {
  echo 'doesn\'t match';
}
?>

Kind regards

-r-