如何使用正则表达式在Python中验证IPv4地址。

选择 | 换行 | 行号
  1. if(re.match("(^[2][0-5][0-5]|^[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})\.([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})$",ip_addr)   != None):
  2.         print "Verified as passed"
  3. else:
  4.         print "Verified as failed"
# 回答1

你好知道如何在python中接受ipv4格式的ip地址作为用户输入吗?使用input()函数,它不接受多个十进制输入!!谢谢
# 回答2

使用raw_input()而不是input(()来接收用户的输入。我接受了abeesh ks的重新模式并添加了评论:

选择 | 换行 | 行号
  1. import re
  2.  
  3. ip_addr = "This is an example of an IPv4 address: 192.11.2.250"
  4.  
  5. patt = re.compile('''
  6.             ^                                       # Match start of string
  7.             ([2][0-5][0-5]|^[1]{0,1}[0-9]{1,2})     # Match decimal octet
  8.             \.                                      # Match '.' character
  9.             ([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})    # Match decimal octet
  10.             \.                                      # Match '.' character
  11.             ([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})    # Match decimal octet
  12.             \.                                      # Match '.' character
  13.             ([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2})    # Match decimal octet
  14.             $                                       # Match end of string
  15.             ''', re.VERBOSE)
  16.  
  17. m = re.search(patt, ip_addr.split()[-1])
  18.  
  19. if m:
  20.     print "Valid IPv4 address"
  21. else:
  22.     print "Invalid IPv4 address"
  23.  
  24. print m.groups()

我还没有验证重新模式是否100%有效,但它似乎有效。

# 回答3

谢谢abeesh/bvdet。我将试用代码:)

标签: python

添加新评论