sss
sss

Reputation: 69

Testing an ip address with regex

Im trying to test the following strings of ip addresses for validity, such as:

1.1.1.1/8
15.10.30.100/16
100.10.10.44/24
198.30.20.30/32

and I have the following regex that tests whether each item of ip:

 !/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]\/\/(/^\d+)/ig?)$/.test(item.trim())

But im not sure how about the part where there is a forward slash followed by a number such as /24, /32... which is \/\/(/^\d+)/ig. Could anybody point what i did wrong here?

Upvotes: 0

Views: 207

Answers (2)

Cheloide
Cheloide

Reputation: 805

I did not check the error in your regex but I here's a working one

(?:(?:25[0-5]|[0-2]?[0-4]?[0-9]|[0-1]?[0-9]?[0-9])\.){3}(?:(?:25[0-5]|[0-2]?[0-4]?[0-9]|[0-1]?[0-9]?[0-9]))(?:\/(?:3[0-2]|[1-2]?[0-9])|$)$

Test it here

The regex should check allocation blocks from 0 to 32 and IP4 without it.

If you want to check specific allocation blocks you should use this one

(?:(?:25[0-5]|[0-2]?[0-4]?[0-9]|[0-1]?[0-9]?[0-9])\.){3}(?:(?:25[0-5]|[0-2]?[0-4]?[0-9]|[0-1]?[0-9]?[0-9]))(?:\/(?:8|16|24|32)|$)

and filtering blocks inside the last nested non-capturing group (?:8|16|24|32)

Test it here

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626754

You must have had trouble pasting the regex from an online regex tester to the JS code. However, there are issues here: 1) you have \/\/ that requires // to appear in the string, 2) you added ^ anchor close to the end of the pattern (and since it requires the start of string position, it prevented your regex from matching). Besides, no need for g and i modifiers, you only test the whole string against the pattern that has no letters in it.

Use

/^(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}\/(?:[12]?\d|3[0-2])$/

See the regex demo.

In JS, you may build the pattern dynamically for better readability:

var octet = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
var rx = new RegExp("^" + octet + "(?:\\." + octet + "){3}/(?:[12]?\\d|3[0-2])$");
var strs = [ "1.1.1.1/8", "15.10.30.100/16", "100.10.10.44/24", "198.30.20.30/32", "1.1.1.1/0", "1.1.1.1/32", "1.1.1.1/33"];
for (var s of strs) {
  console.log(s, "=>", rx.test(s));
}

Pattern details

  • ^ - start of string
  • (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) - an octet pattern, 0 to 255
  • (?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3} - 3 occurrences of:
    • \. - a dot
    • (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) - an octet pattern
  • \/ - a slash
  • (?:[12]?\d|3[0-2]) - an opptional 1 or 2 followed with any digit (0 to 29, matched with [12]?\d), or 3 followed with digits from 0 to 2 (30 to 32)
  • $ - end of string.

Upvotes: 1

Related Questions