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?

12
  • 1
    you want to extract 000.000.000.000 ? Commented Oct 17, 2022 at 9:13
  • 1
    doesn't just a text.split(",")[0] work for you ? Commented Oct 17, 2022 at 9:16
  • 1
    Then perhaps text.split(',')[0].strip(' "') Commented Oct 17, 2022 at 9:29
  • 1
    Does this help? Regex: how to extract only first IP address from string (in Python) - demo Commented Oct 17, 2022 at 9:32
  • 1
    @bobblebubble congrats on your gold regex badge! :) Commented Oct 17, 2022 at 9:36

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

This would match 12356345.34578348753.23487234.287342735
yes it would, is this a problem?
Well, that's not a valid IP address...
I would not use regex to verify the ip, but to get a pattern that I can process from there on. Parsing the ip is another story, but I added a function to my answer to show what I mean.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.