RydallCooper
RydallCooper

Reputation: 21154

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 statement I need another one to recognize any IP address just not 127.0.0.1. What's the easiest way of doing this?

Upvotes: 0

Views: 221

Answers (3)

signus
signus

Reputation: 1148

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.

Upvotes: 2

cmd
cmd

Reputation: 5830

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.

def is_ipaddress(s):
    try:
        return all(0 <= int(o) <= 255 for o in s.split('.', 3))
    except ValueError:
        pass
    return False

then

string = "!ip 127.0.0.1"
command, param = string.split()
if command == '!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

Upvotes: 1

Chris Arena
Chris Arena

Reputation: 1620

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)
    return True
except ValueError as e:
    return False

Upvotes: 1

Related Questions