user544079
user544079

Reputation: 16629

Regex for IPV4 addresses giving invalid response

I want to filter all IPV4 addresses

var regex = new RegExp(/^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$/);

regex.test('140.1.2.3');   // gives false should give true

any 0 in the 1st term gives false

What needs to change?

Upvotes: 0

Views: 228

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

If you have a list of IPv4 addresses, and you want to filter them out, there is no need in a fancy validating-style regex. Here is a modified Ben Mc Cormick's function for your case:

function checkIsIPV4(entry) {
  if (entry === "0.0.0.0" || entry === "255.255.255.255") {
    return false;
  }
  var blocks = entry.split(".");
  if(blocks.length === 4) {
    return blocks.every(function(block) {
      return parseInt(block,10) >=0 && parseInt(block,10) <= 255;
    });
  }
  return false;
}
var strs = ["100.1.2.3", "0.0.0.0", "0.0.0.1", "255.255.255.254", "255.255.255.255", "255.255.255.256"];
for (var s of strs) {
  document.body.innerHTML += s + ": " + checkIsIPV4(s) + "<br/>";
}

If you really need to use a validating style regex that will match all IP addresses excluding all zeros and all 255s:

var re = /^(?!(?:0(?:\.0){3}|255(?:\.255){3})$)([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$/;

See the regex demo

Initially, you had double backslashes while you need single ones in the regex literal. Note that it is a negative lookahead (?!(?:0(?:\.0){3}|255(?:\.255){3})$) that disallows 0.0.0.0 and 255.255.255.255.

Upvotes: 1

Related Questions