0

I have a string of variable length, which include different IPs and it can be in this form:

\"000.000.000.000\"

or this form:

\"000.000.000.000, 111.111.111.111\"

I would like to come up with a way to be able to parse the first IP without knowing beforehand if the string includes only one IP or more. Is there a way to achieve that?

Kosmylo
  • 436
  • 1
  • 6
  • 20

1 Answers1

2

I think I would choose regex for this. It handles most of your cases, you don't have to care about the surrounding noise like spaces or slashes and you can loop through the result.

import re


def verify_ip(ip_address: str) -> bool:
    ip_segments = ip_address.split('.')
    if len(ip_segments) != 4:
        return False
    for segment in [int(ip_segment) for ip_segment in ip_segments]:
        if not 0 < segment < 255:
            return False
    return True


raw_string = '\"0156165100.000.000.000,111.111.111.111,192.168.1.1.10.15 1 68 3+- 41as asdfvyxcv 10.10.10.10\"'
pattern = r'\d+\.\d+\.\d+\.\d+'
matches = re.findall(pattern, raw_string)
for ip in matches:
    print(f'{ip if verify_ip(ip) else "bad ip"}')

Result:

bad ip
111.111.111.111
192.168.1.1
10.10.10.10
Ovski
  • 575
  • 3
  • 14