Skip to content Skip to sidebar Skip to footer

Python Recognizing An Ip In A String

I'm having a lot of trouble with this segment of code: command = '!ip' string = '!ip 127.0.0.1' if command in string: That's where I get stuck. After the first if st

Solution 1:

I would give it a shot using regular expressions, where the regular expression (?:[0-9]{1,3}\.){3}[0-9]{1,3} is a simple match for an IP address.

    ip = '127.0.0.1'

    match = re.search(r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}', ip)
    # Or if you want to match it on it's own line.# match = re.search(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', ip)if match:                      
         print"IP Address: %s" %(match.group)
    else:
         print"No IP Address"

Regular expressions will make your life much easier when doing data matching.

Solution 2:

Try to create an ipaddress out of it. If it fails, it's not an IP address. This means you'd have to be able to remove the "!ip" portion of the string, which is probably good practice anyway. If this isn't possible, you can split on whitespace and take the ipaddress portion.

import ipaddress

try:
    ipaddress.ip_address(string)
    returnTrueexcept ValueError as e:
    returnFalse

Solution 3:

not sure what your input looks like, but if you are not needing to search for the address (meaning you know where it should be) you could just pass that string to something like this.

defis_ipaddress(s):
    try:
        returnall(0 <= int(o) <= 255for o in s.split('.', 3))
    except ValueError:
        passreturnFalse

then

string = "!ip 127.0.0.1"command, param = string.split()
ifcommand == '!ip':
    if not is_ipaddress(param):
        print'!ip command expects an ip address and ', param, 'is not an ip address'else:
        print'perform command !ip on address', param

Post a Comment for "Python Recognizing An Ip In A String"