0

I need an regex which will match following pattern a.b.c.d /nn, for example 192.168.0.24 /32.

Meanwhile I'd like to do some validations, so that in the octets the first number could be only 1 or 2, if the last 3 octets consist only 1 number it can be 0 too. In addition the numbers of octets should be up to 255. In the similar way for /nn, the first digit should be only from 1 to 3, but if it is 3, the second should be from 0 to 2, if the first is absence, then the only number should be from 1 to 9.

I could wrote pattern like this

(?<!\d)(?!0|4|5|6|7|8|9)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} +/(?<!\d)(?!0|4|5|6|7|8|9)\d{1,2}

but for example 192.168.740.056 /39 matches it as well.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
A M
  • 3
  • 2

1 Answers1

0

Does this work for you?

def find_ips(ip_string):
    for match in re.finditer(r'(?P<ip>[12]\d*\.\d+\.\d+\.\d+)\s+/(?P<mask>\d+)', ip_string):
        octets = list(map(int, match.group('ip').split('.')))
        if all(0 <= octet <= 255 for octet in octets) and int(match.group('mask')) <= 32 and octets[-1] > 0:
            yield match.group()

# ips = ['192.168.0.1 /32', '22.22.22.22 /32']
ips = list(find_ips("ip1=8.8.8.8 /32; ip2=192.168.0.1 /32; ip3=22.22.22.22 /32; ip4=192.168.740.056 /39"))
Thy
  • 468
  • 3
  • 5
  • Thanks. I'll examine your code and will get back with my answer, since I am still not good at coding. However, I could achieve this just with one line, it is kinda long, though works fine. (1[0-9][0-9]|2[0-5][0-5]|[1-9][0-9](?=)|[1-9])\.(1[0-9][0-9]|2[0-5][0-5]|[1-9][0-9](?=)|[0-9])\.(1[0-9][0-9]|2[0-5][0-5]|[1-9][0-9](?=)|[0-9])\.(1[0-9][0-9]|2[0-5][0-5]|[1-9][0-9](?=)|[0-9]) +/(1[0-9]|2[0-9]|3[0-2](?=)|[1-9]) – A M Dec 31 '21 at 15:51