使用raw_input()而不是input(()来接收用户的输入。我接受了abeesh ks的重新模式并添加了评论:
- import re
-
- ip_addr = "This is an example of an IPv4 address: 192.11.2.250"
-
- patt = re.compile('''
- ^ # Match start of string
- ([2][0-5][0-5]|^[1]{0,1}[0-9]{1,2}) # Match decimal octet
- \. # Match '.' character
- ([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2}) # Match decimal octet
- \. # Match '.' character
- ([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2}) # Match decimal octet
- \. # Match '.' character
- ([0-2][0-5][0-5]|[1]{0,1}[0-9]{1,2}) # Match decimal octet
- $ # Match end of string
- ''', re.VERBOSE)
-
- m = re.search(patt, ip_addr.split()[-1])
-
- if m:
- print "Valid IPv4 address"
- else:
- print "Invalid IPv4 address"
-
- print m.groups()
我还没有验证重新模式是否100%有效,但它似乎有效。