[Tutor] Validating String contains IP address

Mats Wichmann mats at wichmann.us
Fri Mar 31 21:01:24 EDT 2017


On 03/31/2017 06:44 PM, Alex Kleider wrote:
> 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


This assumes "an IP address" is the four dotted numbers characteristic
of IPv4. These days that's a bad assumption unless you're absolutely
sure an IPv6 address can never appear.  Can you?







More information about the Tutor mailing list