Python Recognizing An IP In A String

偶尔善良 提交于 2021-01-29 07:30:52

问题


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?


回答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.




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



回答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.

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


来源:https://stackoverflow.com/questions/22723360/python-recognizing-an-ip-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!