0

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?

RydallCooper
  • 19,094
  • 1
  • 11
  • 17
  • 2
    use a regular expression – Miguel Prz Mar 28 '14 at 21:17
  • Agreed, a regex is the way to go - but don't try to do the whole thing in regex. Instead, just recognize 4 integers separated by dots, collecting the four integers into groups. Then check the groups to make sure they fall between 0 and 255. – dstromberg Mar 28 '14 at 21:31

3 Answers3

2

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.

signus
  • 1,118
  • 14
  • 43
  • note to OP: remove the `^` and `$` from the search if you need to find a match ANYWHERE in the string. `^` indicates the beginning of a string and `$` indicates the end of it, so if the string does not contain EXACTLY an IP address and NOTHING else, this test will fail. – Adam Smith Mar 28 '14 at 22:12
  • 1
    Exactly. I'll just add it as a commented line for suggestion. – signus Mar 28 '14 at 22:20
1

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
Chris Arena
  • 1,602
  • 15
  • 17
1

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
cmd
  • 5,754
  • 16
  • 30