Today, one of my costumers asked me to create some groups and Live Maps views containing network devices with a specific ip address range. Now, im a big fan of the “work smarter, not harder” principle, so I wanted the groups and views to be dynamic using regular expressions.

I’ve worked with regular expressions before, which is fairly manageable with a table of the meta characters on your hand. However, I find ip addresses a lot more tricky, which is why I’m posting different solutions.

Before advancing, I would like to introduce you to a dear friend of mine: www.regexpal.com. On regexpal.com you can test your regular expressions to make sure they are working.

All possible ip addresses:

^(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$

Yes, this looks pretty complicated, but I’m going to break it down in some examples.

 

Example 1: you want all the ip addresses with an XXX.50.XXX.XXX address:

^(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(50)\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$

clip_image001

 

Example 2: you want all the ip addresses with an XXX.XXX.2.1 address:

^(10|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(2)\.(1)$

 

Example 3: you want ip addresses between the second octets 10.10.10.1 and 10.20.10.1 (10.10.X.X and 10.20.X.X):

^(\d|10)\.(\d|1\d|1\d\d|2([0-9]\d|5[0-9]))\.(10)\.(1)$ = everything between 10.10.10.1 and 10.19.10.1 ^(\d|10)\.(20)\.(10)\.(1)$ = 10.20.10.1, but not 10.21.10.1

clip_image002

 

Example 4: Ip addresses starting with 10:

^(10|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$

 

Example 5:  Ip addresses starting with 192.168.100

^(192|(10-4]\d|5[0-5]))\.(168)\.(100)\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$

 

Using these examples and regexpal.com its a lot easier to make a regular expression. Let me know if you need other examples 🙂

 

Happy regular expressioning!