0

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?

user544079
  • 16,109
  • 42
  • 115
  • 171
  • Note you have 2 `\\d` - they must be turned to `\d`. And no need using `RegExp` constructor. See [`^([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])$`](https://regex101.com/r/dS4rX7/1). Is that just a typo? – Wiktor Stribiżew Apr 15 '16 at 21:53
  • But this allows 0.0.0.0 I want to block 0.0.0.0 and 255.255.255.255 – user544079 Apr 15 '16 at 21:57
  • 2
    Is that the only added requirement or are you going to add "buts" later? Please update your question. – Wiktor Stribiżew Apr 15 '16 at 21:57
  • 1
    Why use a regex in the first place? Why not split on dots, parse the ints and validate the values to be 1..254 or 0..255 or whatever? Even better; parse to a single 32 bit value so you can easily block 0.0.0.0 (e.g. 0 as int32) and 255.255.255.255 (e.g. -1 as int32 (signed) or 0xFFFF). – RobIII Apr 15 '16 at 21:59
  • @RobIII I was thinking exactly the same thing. – robbmj Apr 15 '16 at 21:59

1 Answers1

1

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.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563