Using a RegEx to match IP addresses in Python

后端 未结 13 2471
不思量自难忘°
不思量自难忘° 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:10

    IP address uses following authentication :

    1. 255 ---> 250-255
    2. 249 ---> 200-249
    3. 199 ---> 100-199
    4. 99 ---> 10-99
    5. 9 ---> 1-9

      import re    
      k = 0
      while k < 5 : 
          i = input("\nEnter Ip address : ")
          ip = re.match("^([1][0-9][0-9].|^[2][5][0-5].|^[2][0-4][0-9].|^[1][0-9][0-9].|^[0-9][0-9].|^[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9].|[2][5][0-5].|[2][0-4][0-9].|[1][0-9][0-9].|[0-9][0-9].|[0-9].)([1][0-9][0-9]|[2][5][0-5]|[2][0-4][0-9]|[1][0-9][0-9]|[0-9][0-9]|[0-9])$",i)
          k = k + 1 
          if ip:
              print ("\n=====================")
              print ("Valid IP address")
              print ("=====================")
              break
          else :
              print ("\nInvalid IP")
      else :
          print ("\nAllowed Max 5 times")
      

    Reply me if you have doubt?

提交回复
热议问题