user673906
user673906

Reputation: 847

Regex to find a range in an ip address

For example, on my cisco switch I want to find all results with a second octet between 63-255. So first octet 10. Second octet 64 - 255 Third and fourth octet can be any

So it should like this 10.[64 - 255 ]..

This where I got to

10 \?\ ..* \ ..* 

Thanks

Upvotes: 0

Views: 6007

Answers (1)

user8397947
user8397947

Reputation: 1544

The following regex does what you want (mandatory regex101 link):

10\.(6[4-9]|[7-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(1?\d\d?|2[0-4]\d|25[0-5])\.(1?\d\d?|2[0-4]\d|25[0-5])

It may look complex (mostly because of its length), but it's actually straightforward. Here's a breakdown:

  • 10 matches the first octet which is supposed to be 10
  • \. matches a dot. Same goes for the other \.s
  • (6[4-9]|[7-9]\d|1\d\d|2[0-4]\d|25[0-5]) matches the second octet, making sure it's between 64 and 255 (inclusive) this way:
    • Match a 6 followed by a 4, 5, 6, 7, 8 or 9 6[4-9] (numbers between 64 and 69), or
    • Match a 7, 8 or 9 followed by a digit [7-9]\d (numbers between 70 and 99), or
    • Match a 1 followed by two digits 1\d\d (numbers between 100 and 199), or
    • Match a 2 followed by a 0, 1, 2, 3 or 4, which is then followed by a digit 2[0-4]\d (numbers between 200 and 249), or
    • Match a 2 followed by a 5 followed by a 0, 1, 2, 3, 4 or 5 25[0-5] (numbers between 250 and 255)
  • The first (1?\d\d?|2[0-4]\d|25[0-5]) matches the third octet (which can be anything between 0 and 255) this way:
    • Match a digit optionally preceded by a 1 and optionally followed by another digit 1?\d\d? (numbers between 0 and 199), or
    • Match a 2 followed by a 0, 1, 2, 3 or 4, which is then followed by a digit 2[0-4]\d (numbers between 200 and 249), or
    • Match a 2 followed by a 5 followed by a 0, 1, 2, 3, 4 or 5 25[0-5] (numbers between 250 and 255)
  • The second (1?\d\d?|2[0-4]\d|25[0-5]) matches the fourth octet using the same logic

Upvotes: 4

Related Questions