Damon
Damon

Reputation: 119

Exclude an IP from a regex that extract IPs from text file

I posted a question regarding this before but forgot about an additional case. Here is my first question:

Regex to include and exclude certain IPs

The additional case is this line in routing table:

D*EX 0.0.0.0/0 [170/19664] via 10.10.10.1, 5d22h, Vlan10
           [170/19664] via 10.10.10.1, 5d22h, Vlan20

How to I edit my regex to exclude 0.0.0.0/0 IP from my below regex:

(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\/(?:[\d]{1,3})\b(?! is variably)

I tried these but it did not work:

(?! 0.0.0.0/0)(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\/(?:[\d]{1,3})\b(?! is variably)
                                 AND
(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\/(?:[\d]{1,3})\b(?! is variably)(?! 0.0.0.0/0)

Thanks

Damon

Upvotes: 1

Views: 146

Answers (1)

Chih-Hsu Jack Lin
Chih-Hsu Jack Lin

Reputation: 453

As @Greg Hewgill commented, I think you can use if statement.

if ('0.0.0.0/0' not in text) and ('is variably' not in text):
    match = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\/(?:[\d]{1,3})\b', text)

If you really want to use regex to solve it, this is it. https://regex101.com/r/jTu8cj/2

(?!0\.0\.0\.0/0)(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\/(?:[\d]{1,3})\b(?! is variably)

# Positive
D       10.50.80.0/24 [90/3072] via 10.10.10.1, 3w6d, Vlan10
C       10.10.140.0/24 is directly connected, Vlan240
10.10.140.0/2
10.10.140.0/16
2.2.2.2/24
5.5.5.5.5/24

# Negative
10.0.0.0
     10.10.60.0/16 is variably subnetted, 58 subnets, 4 masks
0.0.0.0/0 [170/19664] via 10.10.10.1, 5d22h, Vlan10

Upvotes: 1

Related Questions