Using a RegEx to match IP addresses in Python

后端 未结 13 2455
不思量自难忘°
不思量自难忘° 2020-12-01 04:58

I\'m trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address...

As a simple test, I have the following...

imp         


        
13条回答
  •  再見小時候
    2020-12-01 05:13

    import re
    ipv=raw_input("Enter an ip address")
    a=ipv.split('.')
    s=str(bin(int(a[0]))+bin(int(a[1]))+bin(int(a[2]))+bin(int(a[3])))
    s=s.replace("0b",".")
    m=re.search('\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}$',s)
    if m is not None:
        print "Valid sequence of input"
    else :
        print "Invalid input sequence"
    

    Just to keep it simple I have used this approach. Simple as in to explain how really ipv4 address is evaluated. Checking whether its a binary number is although not required. Hope you like this.

提交回复
热议问题