user2998266
user2998266

Reputation: 51

Regular Expression for IP subnet with exclusion

I am trying to set up an XML config file for TACACS. I am not the best at REGEX.

Essentially you can specify a group of clients. They make this easy to do if you want to include a whole subnet with:

      <Client>192.168.100.*</Client>

The problem I am running into is that I want to do different things for different clients (firewalls). For example, I want to say all clients in subnet 192.168.100.* EXCEPT for 192.168.100.127.

I immediately noticed a couple of problems.

192.168.100.[1-9][0-9] should cover 192.168.100.10-99 but grabs triple digit IPs in the last octet as well. Like 192.168.100.101 because it matches the 10 in 101. Same problem for 192.168.100.[1-9] as it grabs the first digit.

How do I force it to only grab one or two digits?

As for the exclusion I tried: 192.168.100.1[0-9][^7] It managed to not grab 192.168.100.127 but grabbed 192.168.100.11 as well when it should only be checking 100-199.

Any help would be appreciated. Thanks.

Upvotes: 0

Views: 936

Answers (3)

Bohemian
Bohemian

Reputation: 425298

Add a word boundary \b to the end of the IP, eg:

192.168.100.[1-9][0-9]\b

The word boundary, which doesn't consume any input, asserts that there isn't another digit.

For the "not 127" example, use this:

192.168.100.1[0-9][^7<]

Because [^7] will also match a following open bracket.

Upvotes: 0

Maciej Kozieja
Maciej Kozieja

Reputation: 1865

Will this work for you? ((?:2[0-5][0-5]|1\d\d|\d{1,2})\.(?:2[0-5][0-5]|1\d\d|\d{1,2})\.(?:2[0-5][0-5]|1\d\d|\d{1,2})\.(?:2[0-5][0-5]|1[^2][^7]|\d{1,2}))$

Upvotes: 0

Toto
Toto

Reputation: 91518

Use the regex for ip:

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

and add a negative lookahead before the last part of ip:

^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\.){3}(?!127)([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$
//                                      here __^^^^^^^

For your specific address:

^192.168.100.(?!127)([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$

This will accept all the range 192.168.100.0 to 192.168.100.255 except 192.168.100.127

Upvotes: 1

Related Questions