[Tutor] Validating String contains IP address

Alex Kleider akleider at sonic.net
Fri Mar 31 20:44:22 EDT 2017


On 2017-03-31 16:35, Ed Manning wrote:
> What's the best way to validate a string contains a IP address
> Sent from my iPad
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

The re module perhaps?

How about:

import re

ip_regex = r"""
[12]?\d?\d[.]
[12]?\d?\d[.]
[12]?\d?\d[.]
[12]?\d?\d
"""

ip_pattern = re.compile(ip_regex, re.VERBOSE)

# then test for ip_pattern.search(source).group():
res = ip_pattern.search(source).group()
if res:
     print("IP is {}".format(res))
else:
     print("Source doesn't contain an IP address")

# This assumes that an address would never be written as follows: 
076.191.211.205


More information about the Tutor mailing list